Algorithms · Heaps

Kth Largest Element

Find the k-th biggest number.

The problem

Return the k-th largest number in nums (k = 1 is the biggest). Repeated numbers count separately: in [7, 7, 3] the 2nd largest is 7.

kth_largest([3, 2, 1, 5, 6, 4], 2)5
kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)4
Heaps. Always know the biggest. A hospital waiting room: the most urgent patient is always seen next.

Start with the way that works

This version is correct. It is also the slow one. Read it first: the fast way is easier to find once you can see what the slow way wastes.

def kth_largest(nums, k):take the numbers and k
nums = nums[:]work on a copy
for _ in range(k - 1):k - 1 times…
nums.remove(max(nums))…find the biggest and throw it away (two scans!)
return max(nums)now the biggest left is the answer

Now ask: what if there were a billion?

Search engines keep the top 10 results out of millions of matches with exactly this: a heap that never holds more than 10. Apache Lucene (inside Elasticsearch) has its own little priority queue for it.

Aim for O(n log n)🧩 classic

Think it through

To find the 3rd largest, do you need the top 3 in order?

  • Yes
  • No: only the smallest of the top 3
Show the answer

No: only the smallest of the top 3. The 3rd largest is the smallest of the top 3. So keep the top k and always know their smallest.

A new number arrives and you’re holding k. What do you drop?

  • The biggest
  • The smallest of the k + 1
Show the answer

The smallest of the k + 1. A min-heap of size k: push, and if it grows past k, pop the smallest. Its top is your answer. Same trick as “top 10 songs this hour” on a stream.

Stuck? 3 nudges, smallest first
  1. You don’t care about the order of the top k. You only care about the smallest of them.
  2. Keep a heap of the k biggest numbers seen so far. Its top (the smallest of them) is your answer.
  3. For each x: heappush(top, x); if len(top) > k, heappop(top). Return top[0].

The fast way

Try it yourself before you open this. The slow version above already passes every test, so you can change it one step at a time.

Show the fast version
import heapqPython's heap tools
def kth_largest(nums, k):take the numbers and k
top = []the k biggest so far; the smallest of them on top
for x in nums:look at each number once
heapq.heappush(top, x)add it
if len(top) > k:more than k?
heapq.heappop(top)drop the smallest
return top[0]the smallest of the top k is the k-th largest

Where it’s used for real

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with heaps