Skip to content

Algorithms

Boyer-Moore Majority Vote

O(n) time — one pass through the list · O(1) space.

The idea, in plain English

Imagine a room where more than half the people wear red, and everyone else wears some other color. If you keep pairing up one red person with one non-red person and sending both out of the room, red still wins in the end. There were simply more of them to begin with. The Boyer-Moore trick works the same way. It cancels one 'vote' for the current leading candidate against one vote for anything else. Whoever is left standing at the end is the majority.

How it works

  1. 1Keep a 'candidate' and a 'count', and start count at 0.
  2. 2For each item: if count is 0, make this item the new candidate. Then add 1 to count if the item matches the candidate, or subtract 1 if it does not.
  3. 3After one full pass, the candidate is the majority item — the value that appears more than half the time. This only works when such a majority actually exists in the list.

When you'd use it

Use it to find an item that appears more than half the time in a list, like the winning candidate in an election tally. It does this in a single pass, using almost no extra memory, instead of counting every distinct value with a hash map.

Common beginner mistakes

  • Trusting the result without checking that the list actually has a majority item. If no value appears more than half the time, this algorithm still returns some candidate, just not a valid majority.
  • Resetting the candidate on every mismatch, instead of only when count reaches exactly 0. This breaks the cancellation logic.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Votes: 2 2 1 1 1 2 2
Majority element: 2

See it in motion

Watch votes cancelBoyer-Moore majorityO(n) time — one pass through the list · O(1) space.

One candidate, one count. Press play to cancel votes down to the majority.

—
Candidate
0
Count
—
Majority
0/14
Step
0.0s
Now votingValue 1Value 2Value 3

Not sure this is the right topic? See the learning paths → or where this leads →