Top K Elements
Find the k largest, smallest, closest or most frequent items with a size-k heap, quickselect or frequency buckets, and know when each one is the right answer.
Overview
Top K problems ask for the k items that rank highest by some measure: the largest values, the most frequent words, the closest points. Sorting everything costs O(n log n) and throws most of the work away. Three tools do better: a heap of size k, quickselect, and frequency buckets.
The question behind a size-k heap
Keep the k best items seen so far in a heap. For every new item ask one question: is it better than the worst item I am keeping? To answer in O(1), the worst kept item must be at the root. For the k largest values, the worst kept value is the smallest one, so the heap is a min-heap. That is why the heap direction looks backward.
The rule for each next value x follows from that. If fewer than k values are kept, push x. Otherwise compare x with the root. If x is larger, replace the root with x and sift it down; if not, skip x. The root is the weakest of the k kept values, so a new value only has to beat the root to get in.
The same question picks the heap for every kind of ranking.
- k largest: a min-heap of size k. The root holds the smallest kept value, and a new item gets in when it is larger than the root.
- k smallest: a max-heap of size k. The root holds the largest kept value, and a new item gets in when it is smaller than the root.
- k closest to a point: a max-heap by distance, of size k. The root holds the farthest kept point, and a new point gets in when it is closer than the root.
- k most frequent: a min-heap by count, of size k. The root holds the least frequent kept item, and a new item gets in when its count is higher than the root's.
Here are the 3 largest of 4, 9, 1, 7, 3, 8, 2. Each heap is listed in sorted order, so the root is its first value.
- The 4, 9 and 1 arrive while fewer than 3 values are kept, so each is pushed. The heap is 1, 4, 9.
- The 7 is larger than the root 1, so it replaces the root. The heap is 4, 7, 9.
- The 3 is not larger than 4, so it is skipped.
- The 8 is larger than 4, so it replaces the root. The heap is 7, 8, 9.
- The 2 is not larger than 7, so it is skipped. The heap stays 7, 8, 9.
Each of the n values does at most one O(log k) heap operation, so the total is O(n log k) with O(k) memory. The heap never sees the whole input at once, which is why the same code works on a stream.
The lab below runs this trace. Its other two tabs, Quickselect and Buckets, are the other two tools in this chapter.
Sign up free to read the full topic
More Coding & DSA topics
Start free on Cariara · Coding problems · System design studio