Skip to content
StackDecode
Array techniquesAnimated

Moore's Voting (Boyer–Moore Majority Vote)

Cancel out different elements in pairs; the survivor is the majority candidate.

Time

O(n)

Extra space

O(1)

Use it for

Finding an element that appears more than n/2 times.

How it works

  1. Keep a candidate and a counter.
  2. When the counter is 0, adopt the current item as the new candidate.
  3. If the item equals the candidate add 1 to the counter, otherwise subtract 1 (a pair of different items cancels out).
  4. A true majority (more than n/2) cannot be cancelled away, so it survives. Do a second pass to verify.

Watch it run

Loading animation…