Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify.
Problem: Find all values appearing more than ⌊n/3⌋ times with the extended Boyer–Moore vote (two candidates), then verify.
def maj(a):
c1, c2, n1, n2 = None, None, 0, 0
for x in a:
if x == c1: n1 += 1
elif x == c2: n2 += 1
elif n1 == 0: c1, n1 = x, 1
elif n2 == 0: c2, n2 = x, 1
else: n1 -= 1; n2 -= 1
return sorted(c for c in {c1, c2} if c is not None and a.count(c) > len(a) // 3)
print(maj([1, 2, 3, 1, 2, 1, 2, 4, 2]), maj([5, 6, 7, 8]))What is printed?- A. [1, 2] []
- B. [1] [5]
- C. [2] [5]
- D. [2] []
Correct answer: D. [2] []
In the first array 2 occurs 4 times (> 9 // 3 = 3) but 1 occurs exactly 3 times, which is not MORE than 3, so only 2 qualifies. The second array has no value above 4 // 3 = 1. The verification pass is what removes false candidates.
More Coding Interview Problems questions
- Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority. python def…
- A 'shuffle' swaps each position i with a position chosen uniformly from the WHOLE array (0..n−1), for i = 0..n−1. Why is this not a…
- What is the time complexity of this loop? python for i in range(1, n + 1): j = i while j <= n: work() # O(1) j += i
- Problem: Maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best = a[0] for x in…
- Problem: Taking a value v earns v points for EVERY copy of v, but then all copies of v − 1 and v + 1 are deleted. Maximise the points…
- Problem: Travel on given days; passes cost costs[0] (1 day), costs[1] (7 days) and costs[2] (30 days). Minimise the total cost. python def…