Back to solutions
Majority Element II
MediumArraysFind all elements appearing more than n/3 times.
Constraints
- 1 <= n <= 5*10^4
- -10^9 <= nums[i] <= 10^9
Boyer-Moore with two candidates
Time O(n)Space O(1)
At most two values can exceed n/3. Track two candidates with two counters. Each element either matches a candidate (increment its counter), seeds an empty candidate, or cancels one from each counter. A second pass verifies the surviving candidates actually exceed n/3.
Key terms
- Boyer-Moore voting:
- A counting/cancelling technique that finds frequent elements in O(1) space.
- verification pass:
- A second scan to confirm each candidate truly meets the frequency threshold.
// pass 1: find up to two candidates with Boyer-Moore
// pass 2: count occurrences and keep those > n/3
if (c1 > n / 3) res.push_back((int)cand1);
if (c2 > n / 3) res.push_back((int)cand2);Step by step
- Maintain two (candidate, count) pairs. For each value, increment if it matches a candidate.
- Otherwise, if a counter is zero adopt the value as that candidate; else decrement both counters.
- After the pass, count true occurrences of each candidate.
- Output those whose count exceeds n/3, sorted.