Top K Frequent Elements
Medium · Arrays & hashing
Jump to codeReturn the k most frequent distinct integers in a nonempty array. Assume 1 ≤ k ≤ the number of distinct values and that the top-k set is unique. Order does not matter.
Examples
Example 1
nums = [1,1,1,2,2,3] k = 2
Output: [1,2]
Example 2
nums = [1] k = 1
Output: [1]
Constraints
- 1 <= nums.length <= 10^4.
- -1000 <= nums[i] <= 1000
- 1 <= k <= number of distinct elements in nums.
Need a hint?
No frequency can exceed the array length.
Asked in real interviews
Candidates reported versions of Top K Frequent Elements from these company interviews. Some company questions are locked and open with Premium or XP.
- Top K Frequent ValuesAmazon
- Return the Most Frequent Values in an ArrayGoogle
- Find Top K Frequent ElementsNVIDIA
Solution approach
Count each value, then create frequency buckets from 1 through n. Place each distinct value in its frequency bucket. Walk buckets from largest to smallest, collecting values until k have been selected.
Complexity
O(n) expected time and O(n) space.
Python reference solution
def topKFrequent(nums, k):
counts = {}
for value in nums:
counts[value] = counts.get(value, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for value, count in counts.items():
buckets[count].append(value)
answer = []
for count in range(len(nums), 0, -1):
for value in buckets[count]:
answer.append(value)
if len(answer) == k:
return answer
JavaScript solution
function topKFrequent(nums, k) {
const counts = new Map();
for (const value of nums) counts.set(value, (counts.get(value) || 0) + 1);
const buckets = Array.from({length: nums.length + 1}, () => []);
for (const [value, count] of counts) buckets[count].push(value);
const answer = [];
for (let count = nums.length; count > 0; count--) {
for (const value of buckets[count]) {
answer.push(value);
if (answer.length === k) return answer;
}
}
return answer;
}
Java solution
import java.util.*;
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counts = new HashMap<>();
for (int value : nums) counts.merge(value, 1, Integer::sum);
List<List<Integer>> buckets = new ArrayList<>();
for (int i = 0; i <= nums.length; i++) buckets.add(new ArrayList<>());
for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
buckets.get(entry.getValue()).add(entry.getKey());
}
int[] answer = new int[k];
int size = 0;
for (int count = nums.length; count > 0; count--) {
for (int value : buckets.get(count)) {
answer[size++] = value;
if (size == k) return answer;
}
}
return answer;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> topKFrequent(vector<int> &nums, int k) {
unordered_map<int, int> counts;
for (int value : nums) counts[value]++;
vector<vector<int>> buckets(nums.size() + 1);
for (auto [value, count] : counts) buckets[count].push_back(value);
vector<int> answer;
for (int count = (int)nums.size(); count > 0; count--) {
for (int value : buckets[count]) {
answer.push_back(value);
if ((int)answer.size() == k) return answer;
}
}
return answer;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 9 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
1,
1,
1,
2,
2,
3
],
2
][ 1, 2 ]
[
[
1
],
1
][ 1 ]
[
[
4,
4,
4,
6,
6,
7
],
1
][ 4 ]
[
[
1,
2,
2,
3,
3,
3
],
2
][ 3, 2 ]
[
[
0,
0,
0,
1,
2,
2
],
2
][ 0, 2 ]
Drafts are saved per language in this browser when storage is available.