Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find all elements that appear more than ⌊n/3⌋ times.

Problem: Find all elements that appear more than ⌊n/3⌋ times.
def over_third(a):
    c1 = c2 = None; n1 = n2 = 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(over_third([3, 2, 3]), over_third([1, 2, 3, 1, 2, 3, 1, 2]), over_third([4, 4, 5, 6, 7, 8, 9]))
What is printed?
  1. A. [3] [1, 2, 3] []
  2. B. [2, 3] [1, 2] [4]
  3. C. [3] [1, 2] []
  4. D. [3] [1, 2] [4]

Correct answer: C. [3] [1, 2] []

At most two values can exceed n/3, so keep two candidates with Boyer–Moore counters, then verify with a second pass. In the 8-element list 1 and 2 appear 3 times (> 2) but 3 only twice. In the last list 4 survives as a candidate but appears only 2 times, not more than ⌊7/3⌋ = 2, so verification rejects it. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic