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 wantKeepSize
kth largestmin heapk
kth smallestmax heapk
all of the top keither of the above, then read it outk

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

0 of 8 solved

Check yourself

To find the kth largest, which heap and of what size?

What does pushing n values into a size-k heap cost?

In Reorganize String, why is the letter just used held back for one turn?

When is it impossible to arrange letters with no two equal neighbours?