Top K Frequent Elements
Difficulty: Medium
Given a list of numbers and a number k, return the k numbers that occur most often, in any order.
There is always exactly one valid answer.
Examples
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1, 2]
1 appears 3 times and 2 appears 2 times - both occur more often than 3, which appears only once.
Input: nums = [1], k = 1
Output: [1]
Input: nums = [4,4,4,6,6,7], k = 2
Output: [4, 6]
4 appears 3 times, 6 appears 2 times - both more often than 7.
Constraints
1 <= nums.length <= 10^5
k is always valid: 1 <= k <= number of distinct values in nums.
Approach
Every approach starts by counting how often each number appears, which a hash map does in one pass.
The simplest next step is to sort by frequency and take the top k. That's correct, but a full sort is more work than needed.
A faster approach uses one fact: a frequency can't be larger than the list's length. So create an array of "buckets", where bucket f holds every number that occurs exactly f times. Fill the buckets in one pass, then read them from the highest index down until you have k numbers. No sorting needed.
Solutions
Brute Force - Sort by Frequency
Count each number with a hash map, sort the counts from highest to lowest, and take the first k numbers.
function topKFrequent(nums, k) {
const counts = new Map();
for (const num of nums) {
counts.set(num, (counts.get(num) || 0) + 1);
}
const sorted = [...counts.entries()].sort((a, b) => b[1] - a[1]);
return sorted.slice(0, k).map((entry) => entry[0]);
}Time: O(n log n) · Space: O(n)
Optimal - Bucket Sort
Count each number as before. Instead of sorting, create buckets indexed by frequency: bucket[3] holds every number that appears exactly 3 times, and so on. Read the buckets from the highest frequency down to collect the top k.
function topKFrequent(nums, k) {
const counts = new Map();
for (const num of nums) {
counts.set(num, (counts.get(num) || 0) + 1);
}
// buckets[freq] = list of numbers that occur exactly "freq" times
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (const [num, freq] of counts.entries()) {
buckets[freq].push(num);
}
const result = [];
for (let freq = buckets.length - 1; freq >= 1 && result.length < k; freq--) {
for (const num of buckets[freq]) {
result.push(num);
if (result.length === k) break;
}
}
return result;
}Time: O(n) · Space: O(n)