Data Structures & AlgorithmsHardAmazon · Microsoft OA
Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority.
Find the bug: Boyer–Moore majority vote is used WITHOUT the verification pass on an array that may have no majority.
def majority(a):
cand, cnt = None, 0
for x in a:
if cnt == 0: cand = x
cnt += 1 if x == cand else -1
return cand
print(majority([1, 2, 3, 1, 2]))What is printed?- A. 2
- B. 1
- C. None
- D. 3
Correct answer: A. 2
Votes: 1 (cnt 1), 2 cancels it (0), 3 becomes candidate (1), 1 cancels (0), 2 becomes candidate (1). It returns 2 although no value occurs more than n/2 times. The vote only guarantees the right answer when a majority exists; a second counting pass must confirm it.
More Coding Interview Problems questions
- 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…
- Problem: Houses stand in a CIRCLE (the first and last are neighbours); adjacent houses cannot both be robbed. python def robline(a): take…