Given an array nums of size n, return the majority element — the element that appears more than ⌊n/2⌋ times. The majority element always exists.
nums = [3,2,3]3Think of it as elections: each majority vote cancels one minority vote. Since the majority appears more than n/2 times, it can absorb all cancellations from minority elements and still survive with a positive count at the end.
Counting with a hash map works, but uses O(n) space. Sorting and taking the middle costs O(n log n).
Keep a candidate and a counter. A matching value adds 1, and a different value subtracts 1. When the counter hits 0, the next value becomes the new candidate. The majority outnumbers everything else combined, so it survives.
Pair off different values, and the majority survives. Boyer-Moore voting uses one candidate and one counter.
Run the animation above on your own input, or watch the 1:15 video explanation of Majority Element with a dry run and Java code.