Skip to content

Commit 8fffa42

Browse files
authored
Create guess-the-majority-in-a-hidden-array.py
1 parent 23b67f6 commit 8fffa42

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(n), n queries
2+
# Space: O(1)
3+
4+
class ArrayReader(object):
5+
def query(self, a, b, c, d):
6+
"""
7+
:type a, b, c, d: int
8+
:rtype int
9+
"""
10+
pass
11+
12+
def length(self):
13+
"""
14+
:rtype int
15+
"""
16+
pass
17+
18+
19+
class Solution(object):
20+
def guessMajority(self, reader):
21+
"""
22+
:type reader: ArrayReader
23+
:rtype: integer
24+
"""
25+
count_a, count_b, idx_b = 1, 0, None
26+
value_0_1_2_3 = reader.query(0, 1, 2, 3)
27+
for i in reversed(xrange(4, reader.length())):
28+
value_0_1_2_i = reader.query(0, 1, 2, i)
29+
if value_0_1_2_i == value_0_1_2_3: # nums[i] == nums[3]
30+
count_a = count_a+1
31+
else:
32+
count_b, idx_b = count_b+1, i
33+
value_0_1_2_4 = value_0_1_2_i
34+
for i in xrange(3):
35+
value_a_b_3_4 = reader.query(*[v for v in [0, 1, 2, 3, 4] if v != i])
36+
if value_a_b_3_4 == value_0_1_2_4: # nums[i] == nums[3]
37+
count_a = count_a+1
38+
else:
39+
count_b, idx_b = count_b+1, i
40+
if count_a == count_b:
41+
return -1
42+
return 3 if count_a > count_b else idx_b

0 commit comments

Comments
 (0)