Learn / Heaps and priority queues
Top K
To keep the k largest values seen so far, use a min heap of size k: push each value, and pop when the size passes k. The top is then the kth largest. The same idea with a max heap keeps the k smallest. Each value costs O(log k).
How to recognise it
- The question says kth largest, kth smallest, top k or k most frequent.
- Values arrive one by one and you must answer after each.
- You must repeatedly use the most common (or biggest) item, as in rearranging letters.
Why a min heap for the largest
Keep a heap holding the best k values so far. A new value only matters if it beats the weakest of them, and the
weakest is exactly what a min heap keeps on top.
heap = empty min heap
for x in values:
push x
if size > k: pop # the smallest is not among the k largest
answer = heap.top # the kth largest
| You want | Keep | Size |
|---|---|---|
| kth largest | min heap | k |
| kth smallest | max heap | k |
| all of the top k | either of the above, then read it out | k |
For a single answer on a fixed array, quickselect is O(n) on average, but the heap works for streams too.
Greedy with a max heap
Some problems repeatedly use the item that is currently largest: rearrange letters so that equal ones are not next to each other (always place the most common letter that is allowed), or shrink counts to lower a sum of squares (always reduce the biggest). A max heap gives the largest in O(log n) after every change.
Common mistakes
- Using a max heap of all n values for the kth largest: it works but costs O(n) memory and O(n log n) time.
- Forgetting to put a letter back into the heap after it has waited its turn.
Problems
- Kth Largest Element in a Streameasyguide ready
- Kth Largest Element in an Arraymediumguide ready
- Print elements in sorted order using row-column wise sorted matrixmediumguide ready
- Rearrange characters in a string such that no two adjacent are samemediumguide ready
- Minimum sum of squares of character counts in a given string after removing âkâ charactersmediumguide ready
- Kth largest sum continuous subarraysmediumguide ready
- Reorganize Stringmediumguide ready
- Minimum sum of two numbers formed from digits of an arraymediumguide ready