LeetCode #229 Medium

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.
Constraints
  • 1 <= nums.length <= 5 * 10⁴
  • -10⁹ <= nums[i] <= 10⁹
arrayboyer-moorecounting
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def majorityElement(self, nums):
▶3 cand1 = cand2 = None
▶4 count1 = count2 = 0
▶5 for x in nums:
▶6 if x == cand1:
▶7 count1 += 1
▶8 elif x == cand2:
▶9 count2 += 1
▶10 elif count1 == 0:
▶11 cand1, count1 = x, 1
▶12 elif count2 == 0:
▶13 cand2, count2 = x, 1
▶14 else:
▶15 count1 -= 1
▶16 count2 -= 1
▶17 return [c for c in (cand1, cand2) if nums.count(c) > len(nums) // 3]
nums12232slot 1empty×0votesslot 2empty×0votescancelled groupsnone yetcount checkneed more than 1two empty slots, 0 votes each
n5
⌊n/3⌋1an answer must appear more often
At most two values can appear more than 1 times in 5 numbers, because three of them would need more than 5 elements. So two slots are enough. Each slot holds a candidate and its vote count.
nums1takesslot 12232slot 11×1votesslot 2empty×0votescancelled groupsnone yetcount checkneed more than 1slot 1 is empty → 1 takes it
x1index 0
slot 11 (1)
slot 2none (0)
1 matches no candidate and slot 1 is empty, so 1 becomes candidate 1 with one vote.
nums1takesslot 12takesslot 2232slot 11×1votesslot 22×1votescancelled groupsnone yetcount checkneed more than 1slot 2 is empty → 2 takes it
x2index 1
slot 11 (1)
slot 22 (1)
2 matches neither candidate. Slot 1 is busy but slot 2 is empty, so 2 becomes candidate 2.
nums1takesslot 12takesslot 22+1slot 232slot 11×1votesslot 22×2votescancelled groupsnone yetcount checkneed more than 12 matches slot 2 → 2 votes
x2index 2
slot 11 (1)
slot 22 (2)
2 is the candidate in slot 2, so it adds a vote there.
nums1takesslot 12takesslot 22+1slot 23cutboth2slot 11×0votesslot 22×1votescancelled groups123count checkneed more than 13 matches neither → one vote off each
x3index 3
slot 11 (0)
slot 22 (1)
3 differs from both candidates and both slots have votes. One copy of 1, 2 and 3 is dropped together: three different values, so no value loses more than one copy per group. Votes are now 0 and 1.
nums1takesslot 12takesslot 22+1slot 23cutboth2+1slot 2slot 11×0votesslot 22×2votescancelled groups123count checkneed more than 12 matches slot 2 → 2 votes
x2index 4
slot 11 (0)
slot 22 (2)
2 is the candidate in slot 2, so it adds a vote there, even though slot 1 is empty. Checking the empty slot first would put 2 in both slots.
nums1takesslot 12takesslot 22+1slot 23cutboth2+1slot 2slot 11×0votesslot 22×2votescancelled groups123count check11 seenneed more than 11 seen once, not more than 1 → drop
candidate1slot 1
count1needs more than 1
The vote left 1 in slot 1, but the real count is 1, not more than 1. Surviving the vote is not enough, so 1 is dropped.
nums1takesslot 12takesslot 22+1slot 23cutboth2+1slot 2slot 11×0votesslot 22×2votescancelled groups123count check11 seen23 seenneed more than 12 seen 3 times → keep
candidate2slot 2
count3needs more than 1
The vote only says 2 might qualify, so count it in a second pass: 3 copies, more than 1. It is an answer.
nums1takesslot 12takesslot 22+1slot 23cutboth2+1slot 2slot 11×0votesslot 22×2votescancelled groups123count check11 seen23 seenneed more than 1answer: 2
result[2]
Only the candidates whose bars cross the line are kept: [2]. The voting pass and the counting pass each read the array once, with nothing but two slots stored.
05

Common pitfalls

Returning the candidates without counting

✗ Wrong
return [c for c in (cand1, cand2) if c is not None]
✓ Right
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

✗ Wrong
if count1 == 0:
    cand1, count1 = x, 1
elif count2 == 0:
    cand2, count2 = x, 1
elif x == cand1:
    count1 += 1
✓ Right
if x == cand1:
    count1 += 1
elif x == cand2:
    count2 += 1
elif count1 == 0:
    cand1, count1 = x, 1

On [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

✗ Wrong
nums.count(c) >= len(nums) // 3
✓ Right
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 [].

06

Edge cases

A one-element array

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 array contains 0 or 1 (C++ and Java)

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.

07

Complexity

Time
O(n)
Space
O(1)
One voting pass, then one counting pass per candidate: about three passes over nums. Only two candidates and two counts are stored, and the answer holds at most two values.
08

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.