Top K Elements

Find the k largest, smallest, most frequent or closest items with a size-k heap, bucket sort or quickselect.

Intermediate 2 min readLesson 18 of 25

"Find the k largest / smallest / most frequent / closest" is one of the most common interview patterns. Sorting all n items costs O(n log n). A heap of size k costs O(n log k), and the expected-O(n) quickselect is faster still.

When to use this pattern
  • The words top k, k largest/smallest, k most frequent, k closest, kth.
  • Streaming data where you can only keep k items in memory.
  • Rearranging items so the same value never lands next to itself (reorganise string, task scheduler): a max-heap by count.

The counter-intuitive trick

To keep the k largest, use a min-heap of size k. The heap's top is the smallest of the current top k, so it is the one to evict when something bigger arrives. When you finish, the top is the kth largest.

302112536445
k = 2. The min-heap ends with {5, 6}; its top, 5, is the 2nd largest.
Kth largest element
int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> heap = new PriorityQueue<>();     // min-heap
    for (int x : nums) {
        heap.offer(x);
        if (heap.size() > k) heap.poll();                    // evict the smallest
    }
    return heap.peek();
}

Top k frequent: bucket sort in O(n)

Frequencies are between 1 and n, so put each value in bucket[freq] and read the buckets from high to low.

int[] topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> freq = new HashMap<>();
    for (int x : nums) freq.merge(x, 1, Integer::sum);
    List<Integer>[] bucket = new List[nums.length + 1];
    for (var e : freq.entrySet()) {
        if (bucket[e.getValue()] == null) bucket[e.getValue()] = new ArrayList<>();
        bucket[e.getValue()].add(e.getKey());
    }
    int[] res = new int[k];
    int i = 0;
    for (int f = nums.length; f > 0 && i < k; f--)
        if (bucket[f] != null) for (int x : bucket[f]) if (i < k) res[i++] = x;
    return res;
}

Quickselect: expected O(n)

Partition like quicksort, but recurse only into the side that contains index n − k. Randomise the pivot to avoid the O(n²) worst case. (Details: Searching.)

int quickselect(int[] a, int k) {             // kth largest
    int target = a.length - k, lo = 0, hi = a.length - 1;
    Random rnd = new Random();
    while (true) {
        int p = lo + rnd.nextInt(hi - lo + 1);
        swap(a, p, hi);
        int store = lo;
        for (int i = lo; i < hi; i++) if (a[i] < a[hi]) swap(a, i, store++);
        swap(a, store, hi);
        if (store == target) return a[store];
        if (store < target) lo = store + 1; else hi = store - 1;
    }
}

Which approach?

ApproachTimeSpaceBest when
SortO(n log n)O(1)–O(n)Simplest; n small
Heap of size kO(n log k)O(k)Streams, k much smaller than n
Bucket sortO(n)O(n)Keys are bounded (frequencies)
QuickselectO(n) expectedO(1)One-shot, in-memory array
Practice problems
  • Kth Largest Element in an Arraymedium
  • Kth Largest Element in a Streameasy
  • Top K Frequent Elementsbucket sortmedium
  • Top K Frequent Wordstie-break alphabeticallymedium
  • K Closest Points to Originmax-heap of size kmedium
  • Find K Closest Elementsbinary search a windowmedium
  • Sort Characters By Frequencymedium
  • Reorganize Stringmax-heap; alternate the top twomedium
  • Task Schedulermedium
  • Last Stone Weighteasy
Key takeaways
  • k largest ⇒ min-heap of size k (and vice versa).
  • O(n log k) time, O(k) space; works on streams.
  • Bounded keys (frequencies) ⇒ bucket sort in O(n).
  • Quickselect: expected O(n), in place; randomise the pivot.