# Top K Elements

> The Top K Elements is a problem that involves selecting the k largest or smallest elements from a collection, often using algorithms like heaps or quickselect.

## How do I find the top k elements in an array efficiently?

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

- Topic: Various
- Type: concept

## Example

Wrong:

```js
function topK(nums, k) {
  return nums.sort().reverse().slice(0, k);
}
```

Right:

```js
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.

## Related cards

- [Min Heap](https://wonderium.dev/algorithms/min-heap.md)
- [Max Heap](https://wonderium.dev/algorithms/max-heap.md)
- [Quick Select](https://wonderium.dev/algorithms/quick-select.md)
- [.toSorted()](https://wonderium.dev/js/array-to-sorted.md)
- [Map](https://wonderium.dev/js/map.md)

---

- Level: [Algorithms](https://wonderium.dev/algorithms.md)
- HTML version: https://wonderium.dev/algorithms/top-k-elements
- Last updated: 2026-11-25
