Top K Elements
Example
function topK(nums, k) {
return nums.sort().reverse().slice(0, k);
}function topK(nums, k) {
return nums.toSorted((a, b) => b - a).slice(0, k);
}Default sort() compares as strings and mutates the input; toSorted() with a comparator is correct, and a heap is faster for huge n.
Common mistakes
- Calling
nums.sort()without a comparator, which puts 10 before 9. - Building a heap of all n items when a min heap of size k is enough.
Key points
- When k is much smaller than n, code uses a size-k heap, O(n log k), or quickselect, O(n) on average, not a full sort.
- The k largest items use a min heap of size k that drops its smallest item when it grows past k.
- Numeric sorts pass a comparator, since the default
sort()compares values as strings. - The input is not mutated: code uses
toSorted()or sorts a copy instead of callingsort()on it.
Interview questions
What is the time complexity of top k with a heap?
O(n log k) time and O(k) space with a min heap of size k. Sorting the whole array is O(n log n).
Heap vs quickselect for top k: which is faster?
Quickselect averages O(n) but is O(n²) in the worst case and needs the whole array in memory. A heap is O(n log k) and also works on streams.
How do I find the k most frequent elements?
Count with a Map, then take the top k counts with a heap, or bucket the items by frequency for O(n) overall.
