Majority Element II
Majority Element II is LeetCode 229 (Medium). Given an integer array nums of length n, return every value that appears more than ⌊n/3⌋ times, in any order.
- The answer can be empty: nothing promises that such a value exists.
- The follow-up asks for O(n) time and O(1) extra space, which rules out a hash map of counts.
- 1 <= nums.length <= 5 * 10⁴
- -10⁹ <= nums[i] <= 10⁹
Intuition
Three values that each appear more than n/3 times would need more than n elements, so at most two values can qualify. Keep two candidate slots, each with a vote count.
- Vote: a value that matches a slot adds a vote there; a value that finds an empty slot takes it.
- Cancel: a value that matches neither full slot removes one vote from each, throwing away three different values at once.
- Why true answers survive: each cancel removes at most one copy of a value, and there are at most n/3 cancels. A value seen more than n/3 times keeps copies, so it ends in a slot.
Ending in a slot is not enough, so a second pass counts each candidate.
Needing every value above a fixed share of the array, with O(1) extra space, is the signal for candidate voting instead of a count table. With two candidates the method is called extended Boyer-Moore voting, and the share in the question tells you how many candidates to keep.
Approach
Before reading on, work out how many different values can each appear more than n/3 times. Then decide what a value that matches neither candidate should do to the two counts. Aim for O(n) time and O(1) space.
Start with two empty slots
Set both candidates to nothing and both counts to 0. In Python None never equals a number, so an empty slot can't be matched. C++ and Java start the candidates at 0 and 1: two different values, so the two slots never hold the same number.
Add a vote to a matching candidate
For each x, if it equals cand1 add one to count1, else if it equals cand2 add one to count2. Test both matches before anything else, so a value that already owns a slot always strengthens that slot.
Let an empty slot take the value
If x matches neither, and count1 is 0, make x the first candidate with one vote; if instead count2 is 0, it takes the second slot. A count of 0 means the old candidate was fully cancelled, so it has no claim left.
Cancel one vote from each slot
If x matches neither candidate and both counts are above 0, subtract one from each. This drops one copy each of three different values, and dropping such a group never changes which values are above n/3.
Count the two candidates
After the pass, count how often each candidate really appears and keep those seen more than ⌊n/3⌋ times. The vote only promises that every true answer is a candidate, not that every candidate is an answer.
Code in Python, C++ and Java
Common pitfalls
Returning the candidates without counting
return [c for c in (cand1, cand2) if c is not None]
return [c for c in (cand1, cand2) if nums.count(c) > len(nums) // 3]
On [4, 4, 1, 2, 3, 3] the vote ends with 4 and 3 in the slots, but each appears exactly twice, and twice is not more than ⌊6/3⌋ = 2. The right answer is [].
Claiming an empty slot before checking matches
if count1 == 0:
cand1, count1 = x, 1
elif count2 == 0:
cand2, count2 = x, 1
elif x == cand1:
count1 += 1if x == cand1:
count1 += 1
elif x == cand2:
count2 += 1
elif count1 == 0:
cand1, count1 = x, 1On [1, 2, 2, 3, 2], the 3 cancels slot 1 down to 0 while 2 still holds slot 2. The last 2 then claims slot 1 as well, both slots hold 2, and the result is [2, 2] instead of [2].
Using at least instead of more than
nums.count(c) >= len(nums) // 3
nums.count(c) > len(nums) // 3
On [1, 2, 3] the limit is ⌊3/3⌋ = 1 and every value appears once. With >= the candidates 1 and 2 both pass and the result is [1, 2]; the right answer is [].
Edge cases
For [7] the limit is ⌊1/3⌋ = 0, and 7 appears once, which is more than 0. The vote puts 7 in slot 1 and the count keeps it: the answer is [7].
The starting candidates 0 and 1 are just placeholders with 0 votes. If x is 0, the first test matches and count1 goes from 0 to 1, which is the same as taking the empty slot. A placeholder that never appears counts 0 in the final pass, so it is never returned.
Complexity
nums. Only two candidates and two counts are stored, and the answer holds at most two values.Majority Element II FAQ
What is the difference between Majority Element and Majority Element II?
Majority Element (LeetCode 169) asks for the one value seen more than n/2 times and promises it exists, so it needs one slot and no counting pass. Here the limit is n/3, up to two values can qualify, and none is promised, so the method keeps two slots and checks both at the end.
Can I solve it with a hash map instead?
Yes. Count every value in a dictionary, then return the keys whose count is above len(nums) // 3. It runs in O(n) time but needs O(n) space for the counts, so it misses the follow-up's O(1) space.
Does the same idea work for more than n/4 or n/k times?
Yes. At most k − 1 values can appear more than n/k times, so keep k − 1 slots. A value that matches none of them and finds no empty slot removes one vote from every slot, and a final pass counts each candidate. The cost becomes O(n·k) time and O(k) space.