Python 3D Academyবাংলা

Top k and the k-th largest

🌍 In real life. A school talent show has 200 acts, and the judges' board shows only the top 3 scores so far. When a new score comes in, the judges don't re-sort all 200. They look at the lowest of the three on the board: if the new score beats it, the lowest is wiped off and the new score goes up; otherwise nothing changes. At the end, the lowest score on the board is exactly the 3rd best of the whole show.

This is the top k pattern: to find the k largest of n values, keep only k of them, in a min-heap, so the one to throw out is always on top.

The idea in one sentence: to find the k largest values, push each value into a min-heap and pop whenever it holds more than k; the heap then holds the k largest, and its top is the k-th largest.

Its words:

  • top k: the k biggest values (or the k best, by any key)
  • k-th largest: the value that would be at position k if everything were sorted from biggest to smallest
  • size-k heap: a heap that never keeps more than k items
  • heapq.nlargest(k, xs): Python's ready-made top k, sorted from biggest down

How it works, step by step:

  1. start with an empty min-heap top
  2. for each value x: push it
  3. if top now has k + 1 items, pop the smallest: it can't be among the k largest, because k bigger values are in the heap
  4. at the end, top holds the k largest, and top[0] is the smallest of them, the k-th largest

Watch a board of the top 3 scores, [70, 85, 90]: 95 comes in and pushes 70 off; then 60 comes in and is thrown straight back out:

Why it is correct. After each value is handled, the heap holds the k largest values seen so far. That is true at the start (nothing seen), and it stays true. A new value x joins. If the heap now has k + 1 values, the smallest of them can't be among the k largest, because the other k are all at least as big. So popping it leaves exactly the k largest. A min-heap is the right tool because the value we may need to throw out is the smallest of the ones kept, and a min-heap keeps that one on top.

What it costs, by counting. The heap never holds more than k + 1 values, so each push or pop is O(log k). For n values that is O(n log k) time and O(k) memory. Sorting everything is O(n log n) time and O(n) memory. With a million scores and k = 10, each value costs about log₂ 11 ≈ 3.5 levels of work instead of about 20, and only 11 scores are ever kept. When k is close to n, sorting is just as good.

import heapq

def kth_largest(nums, k):
    top = []                             # a min-heap of the k biggest seen so far
    for x in nums:
        heapq.heappush(top, x)
        if len(top) > k:
            heapq.heappop(top)           # throw out the smallest of the k + 1
    return top[0]                        # the smallest of the k biggest: the k-th largest

print(kth_largest([3, 2, 1, 5, 6, 4], 2))
print(kth_largest([7, 7, 7], 1))

import heapq

def top_scores(scores, k):
    top = []
    for s in scores:
        heapq.heappush(top, s)
        if len(top) > k:
            heapq.heappop(top)
    return sorted(top, reverse=True)     # only k values left to sort

print(top_scores([70, 85, 90, 95, 60], 3))
print(heapq.nlargest(3, [70, 85, 90, 95, 60]))   # the same, ready-made

Mistakes and edge cases.

  • a max-heap of everything: pushing all n values and popping k of them works, but it keeps all n values in memory; the size-k min-heap keeps only k
  • returning the wrong end: the k-th largest is top[0]; top[-1] is just the last item in the list, not the biggest
  • duplicates: [7, 7, 7] has 7 as its 1st, 2nd and 3rd largest; the heap keeps repeats, which is what you want
  • k bigger than the number of values: the heap ends with fewer than k items; decide what that should mean before reading top[0]
  • an empty list: there is no k-th largest; top[0] on [] raises IndexError

Quiz

  1. What does this print?

    import heapq
    
    def kth_largest(nums, k):
        top = []                             # a min-heap of the k biggest seen so far
        for x in nums:
            heapq.heappush(top, x)
            if len(top) > k:
                heapq.heappop(top)           # throw out the smallest of the k + 1
        return top[0]                        # the smallest of the k biggest: the k-th largest
    
    print(kth_largest([3, 2, 1, 5, 6, 4], 2))
  2. What does this print?

    import heapq
    print(heapq.nlargest(3, [5, 1, 9, 7, 3]), heapq.nsmallest(2, [5, 1, 9, 7, 3]))
  3. To keep the k largest values, why use a min-heap rather than a max-heap?

    • The value to throw out is the smallest of those kept, and a min-heap has it on top
    • heapq can only make max-heaps
    • A min-heap keeps the values sorted
  4. This is meant to return the k-th largest. Which line is wrong?

    def kth_largest(nums, k):
        top = []
        for x in nums:
            heapq.heappush(top, x)
            if len(top) > k:
                heapq.heappop(top)
        return top[-1]
  5. n values, a heap that never holds more than k + 1. What is the running time?

    • O(n log k)
    • O(n log n)
    • O(k log n)

Coding tasks

  1. Write kth_largest(nums, k): the k-th largest value in nums (k = 1 is the largest; repeats count separately). k is between 1 and len(nums). Use a min-heap that never holds more than k + 1 values.

  2. Write top_scores(scores, k): the k highest scores, from the highest down (fewer if there are fewer than k scores). Keep at most k + 1 scores in a heap while you scan, and sort only what is left.