Find the kth largest number: heap or quickselect?
Question
A shop wants the 3rd biggest order of the day. Write kth_largest(nums, k). It returns the kth largest value, counting duplicates, for 1 <= k <= len(nums). Do it without sorting the whole list.
totals = [40, 15, 70, 15, 90, 70, 25] kth_largest(totals, 3) # 70: the order is 90, 70, 70, ... kth_largest(totals, 1) # 90 kth_largest(totals, 7) # 15
Then compare your idea with quickselect. Which one would you pick, and when?
def kth_largest(nums, k): ...
Show hints (3)
- "KEEP ONLY K"
You don't need to rank all seven totals. Keep only the 3 biggest so far. Which of those 3 must a new total beat?
- "WHICH HEAP"
heapqis a min-heap:heap[0]is always its smallest item. Keep the k biggest totals in it. Thenheap[0]is the one a new total must beat. - "THE LOOP"
Push the first k numbers. After that, if a number is bigger than
heap[0], callheapq.heapreplace(heap, x): it pops the smallest and pushesx. At the end, returnheap[0].
Show checked explanation
Keep a min-heap of the k biggest numbers so far. When a number beats the heap's smallest, replace it. At the end, the top of the heap is the answer: O(n log k) time, O(k) memory, and it works on a stream. Quickselect is O(n) on average, but O(n²) in the worst case, and it needs the whole list.
import heapq def kth_largest(nums, k): heap = [] # the k biggest so far; heap[0] is the smallest of them for x in nums: if len(heap) < k: heapq.heappush(heap, x) elif x > heap[0]: heapq.heapreplace(heap, x) # drop heap[0], add x return heap[0] totals = [40, 15, 70, 15, 90, 70, 25] print(kth_largest(totals, 3)) print(kth_largest(totals, 1), kth_largest(totals, 7)) print(heapq.nlargest(3, totals))
70 90 15 [90, 70, 70]
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is the heap for k = 3 on [40, 15, 70, 15, 90, 70, 25]:
| number | what happens | heap holds | heap[0] |
|---|---|---|---|
| 40 | push | 40 | 40 |
| 15 | push | 15, 40 | 15 |
| 70 | push | 15, 40, 70 | 15 |
| 15 | not bigger than 15: skip | 15, 40, 70 | 15 |
| 90 | replace 15 | 40, 70, 90 | 40 |
| 70 | replace 40 | 70, 70, 90 | 70 |
| 25 | not bigger than 70: skip | 70, 70, 90 | 70 |
The heap always holds the 3 biggest totals so far. Its smallest item is the 3rd biggest, so the answer is 70. Both 70s stay in the heap, so duplicates count. Each push or replace costs O(log k), and the heap never grows past k items.
Quickselect works like quicksort, but follows only one side. Pick a pivot and split the numbers into bigger, equal and smaller. Then keep only the part that holds the answer:
import random def quickselect(nums, k): pivot = random.choice(nums) bigger = [x for x in nums if x > pivot] equal = nums.count(pivot) if k <= len(bigger): return quickselect(bigger, k) if k <= len(bigger) + equal: return pivot smaller = [x for x in nums if x < pivot] return quickselect(smaller, k - len(bigger) - equal)
Say the pivot is 70. Only 90 is bigger, and there are two 70s. So the 2nd and the 3rd largest are both 70, and the search stops at once. The equal group is what handles duplicates.
A random pivot usually cuts away a good part of the list, so the expected cost is O(n). This version copies lists. An in-place version swaps items inside one list.
Which to pick? Use the heap when k is small, when the data is a stream, or when you can't change the list. Use quickselect for one answer from a big list that sits in memory.
Common mistakes
- Calling
set(nums)first. That answers a different question. The 3rd largest distinct total is 40, not 70. Ask the interviewer which one they mean. - Expecting
heapqto give the biggest item first. In Python 3.12 it is a min-heap only. For a max-heap, push-xand negate the value you pop. - Taking the first item as the pivot. On a list sorted from small to large, with k = 1, each step removes only one item: O(n²). For 2,000 such totals, recursion passes the limit of 1000.
- Skipping the check on k. With k = 8 on these 7 totals, the heap holds all 7, and the code quietly returns 15. Raise
ValueErrorunless1 <= k <= len(nums).
Follow-up questions
- "The orders arrive as a stream that never ends. Which one now?" The heap.
heap[0]is the answer at any moment, with O(k) memory and O(log k) work per new order. Quickselect needs all the numbers in one list, so it can't run on a stream. - "What is the worst case of quickselect, and how do you avoid it?" O(n²), when every pivot is the biggest or smallest value left. A random pivot makes that very unlikely, and the expected cost is O(n). The median-of-medians pivot guarantees O(n) in the worst case, but it is slower in practice.
- "Is there a library function for this?" Yes.
heapq.nlargest(k, nums)[-1]: it returns the k biggest values in order. The docs say it equalssorted(nums, reverse=True)[:k]. For k close to n,sorted(nums)[-k]is usually faster.
What a strong answer covers
Asks whether duplicates count before coding. Explains why a min-heap, not a max-heap, keeps the k largest. Gives O(n log k) and O(k) memory. Knows quickselect is O(n) on average but O(n²) in the worst case, and that a random pivot avoids it in practice.
Open in interactive practice deck →