Majority Element II
Difficulty: Medium · Pattern: Hashing · LeetCode #229
Return all elements appearing more than ⌊n/3⌋ times, in any order. Follow-up: O(1) extra space.
Examples
text
[3, 2, 3] → [3]
[1] → [1]
[1, 2] → [1, 2]Hints
- At most two values can appear more than n/3 times.
- Generalize Boyer–Moore voting to two candidates, then verify their counts.
Approach
Maintain two candidates with counters. For each x: if it matches a candidate, increment that counter; else if a counter is 0, replace that candidate; else decrement both counters. Survivors are only possible answers, so make a second pass to count them and keep those with more than n/3 occurrences. O(n), O(1).
Complexity
Time: O(n). Space: O(1).
Python solution
def majorityElement(nums):
c1 = c2 = None; n1 = n2 = 0
for x in nums:
if x == c1: n1 += 1
elif x == c2: n2 += 1
elif n1 == 0: c1, n1 = x, 1
elif n2 == 0: c2, n2 = x, 1
else: n1 -= 1; n2 -= 1
return [c for c in {c1, c2} if c is not None and nums.count(c) > len(nums) // 3]JavaScript solution
function majorityElement(nums) {
let c1 = null, c2 = null, n1 = 0, n2 = 0;
for (const x of nums) {
if (x === c1) n1++;
else if (x === c2) n2++;
else if (n1 === 0) { c1 = x; n1 = 1; }
else if (n2 === 0) { c2 = x; n2 = 1; }
else { n1--; n2--; }
}
return [...new Set([c1, c2])].filter((c) => c !== null && nums.filter((x) => x === c).length > Math.floor(nums.length / 3));
}