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?
  1. A. [1, 2] []
  2. B. [1] [5]
  3. C. [2] [5]
  4. 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

Exams that ask this topic