169. Majority Element
On LeetCode ->Problem¶
Given a non-empty array where one value appears more than half the time, return that value.
- Example:
Key trick¶
Use Boyer-Moore voting.
- Keep a
candidateand acount. - Same value increases
count. - Different value decreases
count. - Pairs of different values cancel, so the true majority survives.
Trap¶
- Forgetting that the guarantee matters: without it, Boyer-Moore may need a final verification pass.
- Updating the candidate in the wrong order when
count == 0. - Overusing a hash map when the follow-up asks for \(O(1)\) space.
Why is it interesting?¶
It looks like a counting problem, but the best solution is a greedy cancellation idea.
- It turns a frequency task into a neat invariant-based scan.
- It is a classic example of getting \(O(n)\) time and \(O(1)\) space.
Python solution¶
class Solution:
def majorityElement(self, nums: list[int]) -> int:
# Boyer-Moore voting:
# cancel one occurrence of the candidate with one different value.
cand, cnt = None, 0
for x in nums:
if x == cand:
cnt += 1
elif cnt == 0:
cand, cnt = x, 1
else:
cnt -= 1
# Valid because the problem guarantees a majority element exists.
return cand
- Complexity:
- Time: \(O(n)\)
- Space: \(O(1)\)
Comment on my solution¶
Your solution is correct and already the ideal interview answer.
- It uses the right algorithm: Boyer-Moore.
- It meets the follow-up: \(O(n)\) time and \(O(1)\) space.
- Your comment about canceling pairs is the key insight.
Tiny style note:
- Many people check
count == 0first, then compare withcandidate; it reads a bit more directly, but your version is still correct.