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

Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting.

Problem: Find the element that appears more than n/2 times (guaranteed to exist) using Boyer–Moore voting.
static int majority(int[] a) {
    int cand = 0, cnt = 0;
    for (int x : a) {
        if (cnt == 0) cand = x;
        cnt += (x == cand) ? 1 : -1;
    }
    return cand;
}
// majority({2, 2, 1, 1, 1, 2, 2}) + " " + majority({1, 3, 1, 3, 3})
What does the commented expression evaluate to?
  1. A. 1 3
  2. B. 2 3
  3. C. 2 1
  4. D. 1 1

Correct answer: B. 2 3

Pair off different values; the majority survives the cancellations. {2,2,1,1,1,2,2}: the candidate switches to 1 at index 4, then back to 2 at index 6 → 2. O(n), O(1). Without the guarantee a second pass must verify the count.

More Coding Interview Problems questions

Exams that ask this topic