Intuition
Keep a single candidate and a count. Matching votes raise the count, differing votes lower it; when it hits zero, adopt the current element as the new candidate. The true majority survives because it outnumbers everything else combined.
Explanation
Idea
The majority element appears more than half the time, so if every occurrence of the majority is a +1 vote and every other element is a -1 vote, the majority's votes strictly outnumber all others combined. Boyer-Moore voting exploits this with O(1) memory: track one candidate and a running count.
Algorithm
count = 0,candidate = None.- For each
num:- If
count == 0, adoptcandidate = num(start fresh — earlier votes cancelled out). - Then
count += 1ifnum == candidate, elsecount -= 1.
- If
- Return
candidate.
Think of it as pairing off different elements: each -1 cancels one majority vote against one non-majority vote. Because the majority has more than n/2 votes, it can never be fully cancelled, so it is whatever remains as the candidate at the end.
Worked example: [2,2,1,1,1,2,2]
| num | count==0? | candidate | count after |
|---|---|---|---|
| 2 | yes | 2 | 1 |
| 2 | no | 2 | 2 |
| 1 | no | 2 | 1 |
| 1 | no | 2 | 0 |
| 1 | yes | 1 | 1 |
| 2 | no | 1 | 0 |
| 2 | yes | 2 | 1 |
Final candidate = 2, which indeed appears 4 > 7/2 times.
Complexity
- Time: O(n) — one pass.
- Space: O(1) — a candidate and a counter.
Implementation
class Solution {
public int majorityElement(int[] nums) {
int count = 0;
int candidate = 0;
for (int num : nums) {
if (count == 0) {
candidate = num;
}
count += (num == candidate) ? 1 : -1;
}
return candidate;
}
}