ProgrammingHardAmazon OA · Flipkart coding round

What is printed?

What is printed?
def maj(a):
    cand, cnt = None, 0
    for x in a:
        if cnt == 0:
            cand = x
        cnt += 1 if x == cand else -1
    return cand
print(maj([2, 2, 1, 1, 1, 2, 2]), maj([1, 2, 3]))
  1. A. 2 1
  2. B. 2 3
  3. C. 1 3
  4. D. 3 2

Correct answer: B. 2 3

Boyer-Moore voting keeps one candidate and a counter. Value 2 occurs four times out of seven and wins, while [1, 2, 3] ends with 3 as the last remaining candidate.

More Python Programming questions

Exams that ask this topic