Majority element (Boyer-Moore)
Find values that appear more than n/k times with O(k) memory by voting. Each value votes for itself, and a value that matches no candidate cancels one vote from every candidate. A value that is frequent enough survives all the cancelling, and a second pass confirms it.
How to recognise it
- Find the value that appears more than half (or a third, or n/k) of the time.
- You need O(1) or O(k) extra memory, so a full frequency map is not allowed.
- The answer is a value that outnumbers everything else put together.
The idea in one picture
An election with one rule: whenever two people who back different candidates meet, both leave the room. Keep pairing people off until nobody is left who disagrees with anyone. If one candidate had more than half the voters, their supporters cannot all be paired off, so they are the ones still standing. Boyer-Moore voting does this pairing in one pass with a candidate and a counter.
Template: majority (more than n/2)
candidate = none, count = 0
for v in nums:
if count == 0: candidate = v
if v == candidate: count = count + 1
else: count = count - 1
return candidate # if a majority is promised; otherwise count it to check
More than n/k: k - 1 candidates
Keep up to k - 1 candidates, each with a count. A value that matches a candidate adds a vote. A new value takes a
free slot if there is one. Otherwise it cancels one vote from every candidate (and itself), and candidates that reach
0 lose their slot. Each cancellation removes k votes at once, so a value with more than n/k copies cannot lose all
of its votes. Finally, count each surviving candidate to check it is really above the threshold.
A guided example: [2, 2, 1, 1, 1, 2, 2]
| value | candidate | count |
|---|---|---|
| 2 | 2 | 1 |
| 2 | 2 | 2 |
| 1 | 2 | 1 |
| 1 | 2 | 0 |
| 1 | 1 | 1 |
| 2 | 1 | 0 |
| 2 | 2 | 1 |
The survivor is 2, which appears 4 times out of 7.
Common mistakes
- Skipping the second pass when no answer is promised, which reports a survivor that is not frequent enough.
- In the two-candidate version, letting both candidates hold the same value.
- Checking
count == 0after the vote instead of before, so a new candidate never starts with its own vote.
Problems
- Majority Elementeasyguide ready
- Majority Element IImediumguide ready
- Given an array of size n and a number k, fin all elements that appear more than " n/k " timesmediumguide ready