Majority Element II
Medium
Topics
Given an integer array nums of size n, return all elements that appear more than ⌊n/3⌋ times, sorted in ascending order.
Example 1
Input: nums = [3,2,3] Output: [3]
Example 2
Input: nums = [1] Output: [1]
Example 3
Input: nums = [1,2] Output: [1,2]
Constraints
- 1 <= nums.length <= 5*10^4
- -10^9 <= nums[i] <= 10^9
Editorial — intuition, approach, complexity and pitfalls
Intuition
We want every value appearing more than n/3 times. The first thing to establish is how many there can be: three such values would need more than n occurrences between them, so there are at most two. That bound is what makes the problem tractable and is worth stating before any code.
Counting every value and filtering is O(n) time and O(n) space, which is what the shown solution does. The final sort is over at most two values, so it costs nothing.
The O(1)-space answer is Boyer-Moore extended to two candidates, and it is the expected follow-up. Hold two candidate values with two counters; for each element, match it to a candidate, or claim an empty slot, or decrement both. The survivors are the only possible answers — and because the algorithm can produce false positives, a second pass is mandatory to verify each candidate actually exceeds n/3.
Approach
- Count occurrences of each value.
- Return those with
count * 3 > n.
Dry Run
nums = [1,1,1,3,3,2,2,2] n = 8, threshold n/3 = 2.67
counts 1 -> 3 3 -> 2 2 -> 3
1: 3*3 = 9 > 8 qualifies
3: 2*3 = 6 < 8 does not
2: 3*3 = 9 > 8 qualifies
answer [1,2]Using count * 3 > n rather than count > n / 3 keeps the comparison in integers and avoids a rounding question at the boundary.
Complexity
- Time — O(n): one counting pass. The trailing sort is over at most two elements, so it does not affect the bound.
- Space — O(n) for the counter in the worst case of all-distinct values. The two-candidate Boyer-Moore variant is O(1), which is the only reason to prefer it.
Common Pitfalls
- Not knowing the answer has at most two elements. It bounds the problem and is the first thing an interviewer probes.
- Using
>=instead of>. The requirement is strictly more thann/3, so exactlyn/3does not qualify. - Comparing with floating-point division, which can mis-handle the boundary. Multiply instead.
- In the Boyer-Moore variant, skipping the verification pass. The candidates are only possible answers, and without the second pass an input with no qualifying value returns garbage.
- In the Boyer-Moore variant, checking the two candidate slots in the wrong order, so a value matching candidate two is wrongly assigned to an empty candidate one.
Full Solution — all languages
class Solution:
def majorityElement(self, nums):
from collections import Counter
n = len(nums)
cnt = Counter(nums)
return sorted(v for v in cnt if cnt[v] * 3 > n)import java.util.*;
class Solution {
public int[] majorityElement(int[] nums) {
int n = nums.length;
Map<Integer, Integer> cnt = new HashMap<>();
for (int x : nums) cnt.put(x, cnt.getOrDefault(x, 0) + 1);
List<Integer> res = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : cnt.entrySet()) if (e.getValue() * 3 > n) res.add(e.getKey());
Collections.sort(res);
int[] r = new int[res.size()];
for (int i = 0; i < r.length; i++) r[i] = res.get(i);
return r;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<int> majorityElement(vector<int>& nums) {
int n = (int)nums.size();
map<int, int> cnt;
for (int x : nums) cnt[x]++;
vector<int> res;
for (auto& p : cnt) if (p.second * 3 > n) res.push_back(p.first);
sort(res.begin(), res.end());
return res;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var majorityElement = function(nums) {
const n = nums.length;
const cnt = new Map();
for (const x of nums) cnt.set(x, (cnt.get(x) || 0) + 1);
const res = [];
for (const [k, v] of cnt) if (v * 3 > n) res.push(k);
res.sort((a, b) => a - b);
return res;
};