Data Structures & AlgorithmsVery hardProduct company OA

The Boyer–Moore majority vote algorithm (candidate/counter, no verification pass) runs on [3, 4, 4, 4, 4, 1, 3, 4, 4]. What candidate and final counter does it return, and is that candidate really a majority (> n/2)?

  1. A. candidate 4, counter 4; yes
  2. B. candidate 3, counter 3; yes
  3. C. candidate 4, counter 3; yes
  4. D. candidate 4, counter 3; no

Correct answer: C. candidate 4, counter 3; yes

Tracing the vote (increment the counter on a match with the candidate, decrement on a mismatch, replace the candidate when the counter hits 0) leaves candidate 4 with counter 3. Checking by counting shows 4 occurs 6 times out of 9, so it is a true majority — the algorithm must always be verified with a second pass.

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

Exams that ask this topic