Data Structures & AlgorithmsHardHCLTech · Wipro pattern

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

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

Correct answer: A. candidate 5, counter 2; 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 5 with counter 2. Checking by counting shows 5 occurs 5 times out of 8, 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