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?
  1. A. 2
  2. B. 1
  3. C. None
  4. 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

Exams that ask this topic