The home where you level up

Save my spot

Top K Elements

Term side of the Card.
Topic: Various
Unit title: Top K Elements
Categories: Concept
Explanation side of the Card

Explanation: The problem of finding the k largest or smallest elements from a dataset. Common solutions include Heaps, Quick Select and sorting algorithms.

Example

Wrongjs
function topK(nums, k) {
  return nums.sort().reverse().slice(0, k);
}
Rightjs
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 calling sort() 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.

The home where you level up

Daily 3-minute lessons to understand your AI's code.

No spam — just launch news.
Unsubscribe anytime. · Privacy Policy

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy