Home
DSA Patterns
Hash Map
Top K Frequent Elements
Top K Frequent Elements (LeetCode 347)
Top K Frequent Elements (LeetCode 347): return the k most frequent values in an array in O(n) with a count map and buckets indexed by frequency.
Problem Understanding
Top K Frequent Elements: given an integer array nums and an integer k, return the k values that appear most often, in any order. The answer is guaranteed to be unique.
Example: nums = [1, 1, 1, 2, 2, 3], k = 2 returns [1, 2]: 1 appears three times and 2 twice.
Attempt 1: Count, Then Sort by Count
Count every value with a hash map, sort the distinct values by their count in descending order, and take the first k. Counting is O(n), but sorting the m distinct values costs O(m log m): up to O(n log n). The count map is the right first step; the sort is the part to replace.
The Intuition: Counts Are Small Integers
A value can appear at most n times, so its count is an integer from 1 to n. That means counts can be used as array indexes instead of being sorted:
- Count every value in a hash map.
- Make buckets
0..n; put each value intobuckets[count]. - Walk the buckets from
ndown to1, taking values untilkhave been taken.
Every step is linear, so the whole method is O(n): the same idea as bucket sort, applied to frequencies.
Top K Frequent Elements Visualization
k = 2
START
nums
0
1
2
3
4
5
Result
:
count (value:count)
Empty
Find the 2 most frequent values. The count map starts empty
Next
nums[0] = 1: count[1] is now 1
Array
Target
First the array is counted left to right while the count map grows beside it. Then the buckets appear, one row per count from the highest down, and are read from the top; each value taken lights up and joins the result.
Top K Frequent Elements Dry Run
Input: nums = [1, 1, 1, 2, 2, 3], k = 2
| Phase | State |
|---|---|
| Count | {1: 3, 2: 2, 3: 1} |
| Bucket | buckets[3] = [1], buckets[2] = [2], buckets[1] = [3]; buckets 4–6 empty |
| Read 6, 5, 4 | empty |
| Read 3 | take 1: result [1] |
| Read 2 | take 2: result [1, 2], k reached |
Return [1, 2]. Bucket 1 is never read.
Top K Frequent Elements LeetCode Solution
Count map, then buckets indexed by frequency.
Top K Frequent Elements Code
1var topKFrequent = function(nums, k) {2 const count = new Map();3 for (const num of nums) {4 count.set(num, (count.get(num) || 0) + 1);5 }6 const buckets = Array.from({ length: nums.length + 1 }, () => []);7 for (const [num, freq] of count) {8 buckets[freq].push(num);9 }10 const result = [];11 for (let freq = nums.length; freq >= 1; freq--) {12 for (const num of buckets[freq]) {13 result.push(num);14 if (result.length === k) {15 return result;16 }17 }18 }19 return result;20};
Top K Frequent Elements in Python, Java, C++, TypeScript and C
Top K Frequent Elements in Python
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = {}
for num in nums:
count[num] = count.get(num, 0) + 1
buckets = [[] for _ in range(len(nums) + 1)]
for num, freq in count.items():
buckets[freq].append(num)
result = []
for freq in range(len(buckets) - 1, 0, -1):
for num in buckets[freq]:
result.append(num)
if len(result) == k:
return result
return resultTop K Frequent Elements in Java
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>();
for (int num : nums) {
count.merge(num, 1, Integer::sum);
}
List<Integer>[] buckets = new List[nums.length + 1];
for (int i = 0; i < buckets.length; i++) buckets[i] = new ArrayList<>();
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
buckets[e.getValue()].add(e.getKey());
}
int[] result = new int[k];
int taken = 0;
for (int freq = nums.length; freq >= 1; freq--) {
for (int num : buckets[freq]) {
result[taken++] = num;
if (taken == k) {
return result;
}
}
}
return result;
}
}Top K Frequent Elements in C++
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> count;
for (int num : nums) {
count[num]++;
}
vector<vector<int>> buckets(nums.size() + 1);
for (auto& [num, freq] : count) {
buckets[freq].push_back(num);
}
vector<int> result;
for (int freq = nums.size(); freq >= 1; freq--) {
for (int num : buckets[freq]) {
result.push_back(num);
if ((int)result.size() == k) {
return result;
}
}
}
return result;
}
};Top K Frequent Elements in TypeScript
function topKFrequent(nums: number[], k: number): number[] {
const count = new Map<number, number>();
for (const num of nums) {
count.set(num, (count.get(num) ?? 0) + 1);
}
const buckets: number[][] = Array.from({ length: nums.length + 1 }, () => []);
for (const [num, freq] of count) {
buckets[freq].push(num);
}
const result: number[] = [];
for (let freq = nums.length; freq >= 1; freq--) {
for (const num of buckets[freq]) {
result.push(num);
if (result.length === k) {
return result;
}
}
}
return result;
}Top K Frequent Elements in C
typedef struct {
int key;
int count;
UT_hash_handle hh; // uthash.h, available on LeetCode
} Entry;
int* topKFrequent(int* nums, int numsSize, int k, int* returnSize) {
Entry *counts = NULL, *e, *tmp;
for (int i = 0; i < numsSize; i++) {
HASH_FIND_INT(counts, &nums[i], e);
if (!e) {
e = calloc(1, sizeof(Entry));
e->key = nums[i];
HASH_ADD_INT(counts, key, e);
}
e->count++;
}
int **buckets = calloc(numsSize + 1, sizeof(int *));
int *sizes = calloc(numsSize + 1, sizeof(int));
HASH_ITER(hh, counts, e, tmp) {
if (!buckets[e->count]) buckets[e->count] = malloc(numsSize * sizeof(int));
buckets[e->count][sizes[e->count]++] = e->key;
}
int *result = malloc(k * sizeof(int));
*returnSize = 0;
for (int freq = numsSize; freq >= 1; freq--) {
for (int j = 0; j < sizes[freq]; j++) {
result[(*returnSize)++] = buckets[freq][j];
if (*returnSize == k) {
return result;
}
}
}
return result;
}Edge Cases & Common Mistakes
- k equals the number of distinct values: every non-empty bucket is read; the result is every distinct value.
- One value repeated n times: it lands in bucket
n, the first one read. - Sizing buckets by the number of distinct values: a count can be as large as
n, so the buckets must go up ton. - Returning counts instead of values: the buckets hold values; the bucket index is the count.
Summary
Count with a hash map, then use the counts themselves as indexes so nothing needs sorting. The same count map feeds the heap solution in the Heap / Priority Queue pattern when only O(k) extra space is allowed.
More practice: DSA interview questions with answers · patterns cheat sheet
