Find all elements that appear more than n/3 times in an array.
Problem Statement
Examples
Input: nums = [3, 2, 3]
Output: [3]
Explanation: Combining the input according to Majority Element-II logic yields [3].
Input: nums = [1]
Output: [1]
Explanation: Combining the input according to Majority Element-II logic yields [1].
Input: nums = [1, 2]
Output: [1, 2]
Explanation: Combining the input according to Majority Element-II logic yields [1, 2].
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
There can be at most 2 elements appearing strictly more than n/3 times. Using extended Boyer-Moore voting with two candidates and counters, we cancel triplets of distinct elements. A second verification pass confirms which candidates meet the threshold.
Step-by-Step Approach
- Initialize
cand1 = null, cand2 = null, count1 = 0, count2 = 0. - Pass 1: Find the top two potential candidates.
- Pass 2: Count actual frequencies of
cand1andcand2innums. - If
count > floor(n / 3), include inresult. - Return
resultsorted.
Optimal Implementation (JavaScript)
function majorityElementTwo(nums) {
let cand1 = null, cand2 = null, count1 = 0, count2 = 0;
for (let num of nums) {
if (num === cand1) count1++;
else if (num === cand2) count2++;
else if (count1 === 0) { cand1 = num; count1 = 1; }
else if (count2 === 0) { cand2 = num; count2 = 1; }
else { count1--; count2--; }
}
const result = [];
const threshold = Math.floor(nums.length / 3);
let c1 = 0, c2 = 0;
for (let num of nums) {
if (num === cand1) c1++;
else if (num === cand2) c2++;
}
if (c1 > threshold) result.push(cand1);
if (c2 > threshold) result.push(cand2);
return result.sort((a, b) => a - b);
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Only 1 majority element exists.
- 2 majority elements exist.
- No element occurs > n/3 times: returns [].