Exercise: Top k with a heap

"Find the k largest numbers" is a top interview question. Sorting works, but costs O(n log n). A heap of size k does it in O(n log k), which matters when n is huge and k is small, like the top 10 of a billion scores.

The trick is a min-heap that holds the best k seen so far. Its smallest item, at heap[0], is the one to beat. For each number: if the heap has fewer than k items, push it. Otherwise, if the number is bigger than heap[0], replace the smallest with heapq.heapreplace(heap, x).

Exercise: finish top_k(nums, k) using a heap.

  • Return the k largest numbers, largest first.
  • Equal numbers count separately: [9, 9, 1] with k=2 gives [9, 9].
  • If k is bigger than the list, return all of it, largest first.
  • If k is 0 or less, return [].
  • Don't change nums.

heapq.nlargest does all this for you, but write it yourself here: that's what interviewers ask for.

Press Check to run the tests.