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
- Keep a candidate and a counter.
- When the counter is 0, adopt the current item as the new candidate.
- If the item equals the candidate add 1 to the counter, otherwise subtract 1 (a pair of different items cancels out).
- 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…