Data Structures & AlgorithmsVery hardProduct company OA

Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed?

Boyer–Moore majority vote WITHOUT the verification pass, returning (candidate, final counter). What is printed?
def vote(a):
    cand, cnt = None, 0
    for x in a:
        if cnt == 0: cand = x
        cnt += 1 if x == cand else -1
    return cand, cnt
print(vote([2, 2, 1, 3, 1, 1, 4, 1, 1]), vote([1, 2, 3, 1, 2, 3, 3]), vote([5, 5, 6, 6, 7]))
  1. A. (1, 3) (3, 0) (7, 1)
  2. B. (1, 1) (3, 1) (5, 1)
  3. C. (2, 3) (3, 1) (7, 1)
  4. D. (1, 3) (3, 1) (7, 1)

Correct answer: D. (1, 3) (3, 1) (7, 1)

The vote cancels pairs of different values, so a TRUE majority (> n/2) always survives as the candidate – [2,2,1,3,1,1,4,1,1] gives 1 with net 3. But when no majority exists the survivor is arbitrary: [1,2,3,1,2,3,3] yields 3 although it occurs 3/7 times, and [5,5,6,6,7] yields 7, which occurs once. So a second O(n) counting pass is mandatory before reporting a majority. O(1) space.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic