Boyer–Moore majority vote
Keep a candidate and a count. Matching values increment the count; mismatches decrement. When the count hits 0, pick a new candidate. The majority survives.
Every minority vote cancels one majority vote. Because the majority appears > n/2 times, it cannot be cancelled away.
Algorithm
- Start with no candidate.
- For each
x: if count is 0,xbecomes the candidate; then ±1 the count. - Return the candidate.
- Time
- O(n)
- Space
- O(1)
class Solution: def majorityElement(self, nums: list[int]) -> int: cand = 0 count = 0 for x in nums: if count == 0: cand = x count += 1 if x == cand else -1 return cand