Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Heap (priority queue)

Keeping the k best

Lesson · 9 min read · Heap (priority queue) · Keeping the k best

Why I'd keep the k largest values in a min-heap, what that saves you over sorting, and how it handles duplicates and data that keeps arriving.

The k largest live in a min-heap

When a question asks for the k largest values (or the k-th largest on its own) most students I've taught reach for a max-heap, and I can see why, although it's probably the wrong way round. What you actually want is a small group of k values that you'd consider the best so far, and the only member of that group you ever need to look at is the weakest one, because that's the one a new value has to beat to get in. A min-heap of size k hands you exactly that weakest member at the top.

So you walk through the values once. While the heap has room you just push, and after that every new value gets compared with the top. If it's bigger it evicts the top and goes in, and if it isn't then it can't be among the k largest and you move on. By the time you've seen everything the heap holds the k largest values, and the top of the heap is the k-th largest.

Keep the k largest

topK(nums, k)

  1. I'd start with an empty min-heap and then go through the values one at a time.
  2. Until the heap has k values in it, you're free to push each new one straight in.
  3. After that you'd compare every new value with the top and swap it in only if it's bigger.
  4. When you've seen everything, you'll find the k largest in the heap (with the k-th largest sitting on top).
TimeO(n log k)
SpaceO(k)

I'd count it like this: each value costs at most one pop and one push, and since the heap never grows past k values, you're paying about log k for each one (plus k values of memory).

For the trace I've picked the values 9, 1, 8, 2, 7, 3 with k equal to 3, and you'll probably notice the heap finishes holding 7, 8 and 9, which makes 7 the third largest.

  1. Step 1 / 6
    nums
    90i1182237435
    heap (sorted view)
    90
    top9

    9: the heap has room (1 of 3), so it goes in.

  2. Step 2 / 6
    nums
    9011i82237435
    heap (sorted view)
    1091
    top1

    1: the heap has room (2 of 3), so it goes in.

  3. Step 3 / 6
    nums
    901182i237435
    heap (sorted view)
    108192
    top1

    8: the heap has room (3 of 3), so it goes in.

  4. Step 4 / 6
    nums
    90118223i7435
    heap (sorted view)
    208192
    top2

    2 beats the heap's smallest, 1. Evict 1, insert 2.

  5. Step 5 / 6
    nums
    9011822374i35
    heap (sorted view)
    708192
    top7

    7 beats the heap's smallest, 2. Evict 2, insert 7.

  6. Step 6 / 6
    nums
    901182237435i
    heap (sorted view)
    708192
    top7

    3 is no bigger than the heap's smallest, 7, so it cannot be among the 3 largest. Skip it. Done: the top of the heap, 7, is the 3rd largest.

What it saves you, and when sorting is fine

If the whole array is already in memory you could simply sort it and read the k-th value from the end. That costs O(n log n), and in an interview I'd probably mention it first because it's correct and quick to write. The heap starts to pay off when k is small compared with n. With a million values and k equal to 10 the logarithm of n is about 19.9 and the logarithm of k is about 3.3, which means each value needs roughly a sixth of the comparisons. You'd also be keeping just ten values in memory, which matters more than people expect once the input stops fitting comfortably.

The bigger reason I'd use the heap is that it doesn't need all the data at once. If the values arrive as a stream (prices from a feed, scores from a game that's still going) you can't sort what you haven't seen yet, whereas the heap keeps the current top k up to date after every arrival and can answer the question at any moment. There's also quickselect, which averages O(n) on an array you already have, although it rearranges the array, it's slower in the worst case and it can't handle a stream, so I'd treat it as something to mention once the heap version is working.

Duplicates count as separate values, so in [3, 3, 2] the second largest is 3. A heap of size 2 gets that right without any special handling, because both 3s sit in the heap and the 2 never beats the top.

Problems in this module