Try it first — give it 20 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
Given nums and a number k, return the k values that occur most often. The answer is guaranteed to be unique, and you can return it in any order.
nums = [1, 1, 1, 2, 2, 3], k = 2 → [1, 2] (1 appears 3 times, 2 appears twice)
Start with brute force
- Count each value with a hash map.
- Sort the distinct values by count, largest first.
- Take the first
k.
That's O(n log n) because of the sort. It's a fine first answer — say it, then improve it.
Building the intuition
There are three levels of answer here, and walking an interviewer through them is a great signal:
- Sort by count — O(n log n).
- Min-heap of size k — keep only the
kbest counts seen so far; anything smaller gets popped. O(n log k). Great whenkis tiny compared ton. - Bucket sort — O(n). This is the key observation: a value can appear at most n times. So counts live in the small range
1…n, and we can use the count itself as an array index instead of comparing counts.
Picture n + 1 shelves labelled 0 to n. Put each value on the shelf matching its count. Then walk the shelves from the top down, collecting values until you have k.
The optimal approach
- Count frequencies:
count[value] = times it appears. - Create
buckets, a list ofn + 1empty lists. - For each
(value, c)incount, appendvaluetobuckets[c]. - Walk
cfromndown to1, adding values frombuckets[c]to the answer until it haskvalues.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
from collections import Counter
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
count = Counter(nums) # value -> how many times
# buckets[c] = values that appear exactly c times (c can be 0..n)
buckets = [[] for _ in range(len(nums) + 1)]
for value, c in count.items():
buckets[c].append(value)
result = []
for c in range(len(nums), 0, -1): # most frequent first
for value in buckets[c]:
result.append(value)
if len(result) == k:
return result
return resultclass Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> count; // value -> how many times
for (int x : nums) count[x]++;
int n = nums.size();
vector<vector<int>> buckets(n + 1); // buckets[c] = values seen c times
for (auto& [value, c] : count) {
buckets[c].push_back(value);
}
vector<int> result;
for (int c = n; c >= 1; c--) { // most frequent first
for (int value : buckets[c]) {
result.push_back(value);
if ((int)result.size() == k) return result;
}
}
return result;
}
};class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> count = new HashMap<>(); // value -> how many times
for (int x : nums) count.merge(x, 1, Integer::sum);
int n = nums.length;
List<List<Integer>> buckets = new ArrayList<>(); // buckets[c] = values seen c times
for (int i = 0; i <= n; i++) buckets.add(new ArrayList<>());
for (Map.Entry<Integer, Integer> e : count.entrySet()) {
buckets.get(e.getValue()).add(e.getKey());
}
int[] result = new int[k];
int filled = 0;
for (int c = n; c >= 1 && filled < k; c--) { // most frequent first
for (int value : buckets.get(c)) {
result[filled++] = value;
if (filled == k) break;
}
}
return result;
}
}/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var topKFrequent = function (nums, k) {
const count = new Map(); // value -> how many times
for (const x of nums) count.set(x, (count.get(x) || 0) + 1);
// buckets[c] = values that appear exactly c times
const buckets = Array.from({ length: nums.length + 1 }, () => []);
for (const [value, c] of count) buckets[c].push(value);
const result = [];
for (let c = nums.length; c >= 1; c--) { // most frequent first
for (const value of buckets[c]) {
result.push(value);
if (result.length === k) return result;
}
}
return result;
};Dry run
nums = [1, 1, 1, 2, 2, 3], k = 2, so n = 6
Counts: {1: 3, 2: 2, 3: 1}
Buckets (empty ones omitted): buckets[3] = [1], buckets[2] = [2], buckets[1] = [3]
| c | bucket | answer after |
|---|---|---|
| 6, 5, 4 | empty | [] |
| 3 | [1] | [1] |
| 2 | [2] | [1, 2] → we have k = 2, stop |
Complexity
- Time: O(n). Counting is O(n), filling buckets is O(number of distinct values) ≤ O(n), and the walk touches at most n + 1 buckets.
- Space: O(n) for the counts and buckets.
For comparison: sorting is O(n log n), and the heap is O(n log k) time with O(n + k) space.
Edge cases and traps
- k equals the number of distinct values. You return all of them — the loop handles it.
- All values equal. One bucket at index n holds the single value.
- Bucket size. You need
n + 1buckets (counts go up to n), notn. Off-by-one here crashes. - Stopping mid-bucket. A bucket can hold several values; stop as soon as you've collected k.
Say it in the interview
"I count with a hash map first. Sorting by count would be O(n log n), and a size-k min-heap is O(n log k). But counts are bounded by n, so I can bucket sort: bucket i holds the values that appear exactly i times. Reading buckets from n down to 1 until I have k values gives O(n) time and O(n) space."
Follow-ups interviewers ask
- "What if it's a never-ending stream?" You can't bucket the whole stream; keep counts and a size-k min-heap.
- "Top k frequent words, ties broken alphabetically?" (LeetCode 692) Use a heap with a custom comparator.
- "Which is better in practice, heap or buckets?" Buckets for one-off batch input; the heap when k is small and memory for n buckets is a concern.
Practise the same idea
This is Day 13 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free