A size-k min-heap retains the k largest values seen, so its root is the kth largest.
Problem trace
Separate full stream: evict only the weakest retained occurrence
Input and goalFind the `k`th largest value in an unsorted array.
Seed the candidate heapFor nums = [3,2,1,5,6,4] and k = 2, push 3. The heap has room, so nothing is removed.
heap
3
input[3,2,1,5,6,4]current3processed1 of 6size1 <= k
input
[3,2,1,5,6,4]
current
3
processed
1 of 6
Fill the second slotPush 2. The min-heap orders the two protected candidates as [2,3], with the weaker candidate 2 at the root.
heap
2
3
current2processed2 of 6size2 = kactionkeep both
current
3→2
processed
1 of 6→2 of 6
size
1 <= k→2 = k
Discard an undersized candidatePush 1 to make [1,3,2]. Size 3 exceeds k, so pop root 1; [2,3] still holds the largest two of [3,2,1].
heap
2
3
current1processed3 of 6overflow[1,3,2]actionpop 1
current
2→1
processed
2 of 6→3 of 6
overflow
not shown→[1,3,2]
Raise the protected floorPush 5 to make [2,3,5], then pop 2. The retained candidates become [3,5], so the root threshold rises to 3.
heap
3
5
current5processed4 of 6overflow[2,3,5]actionpop 2
current
1→5
processed
3 of 6→4 of 6
overflow
[1,3,2]→[2,3,5]
Keep the next large valuePush 6 to make [3,5,6], then pop 3. The heap [5,6] is exactly the largest two values seen so far.
heap
5
6
current6processed5 of 6overflow[3,5,6]actionpop 3
current
5→6
processed
4 of 6→5 of 6
overflow
[2,3,5]→[3,5,6]
Reject the last weaker valuePush 4 to make [4,6,5], then pop 4. The protected set remains [5,6] after all six inputs.
heap
5
6
current4processed6 of 6overflow[4,6,5]actionpop 4
current
6→4
processed
5 of 6→6 of 6
overflow
[3,5,6]→[4,6,5]
Read the kth largestThe root is the smallest of the two retained values: min([5,6]) = 5, so the second largest is 5.
heap
5
6
k2arithmeticmin([5,6]) = 5result5
k
not shown→2
arithmetic
not shown→min([5,6]) = 5
result
not shown→5
Recognize it
Use it when an unsorted or streaming input asks for the kth largest item or the largest k items, while sorting every value would retain more order than the answer needs.
Keep true
After each input is pushed and any size-(k+1) overflow root is popped, the heap contains exactly the largest min(k, processed) values seen; its root is the weakest retained candidate.
Reuse it
For a bounded best-k set, choose the opposite heap polarity: a min-heap protects the largest k and a max-heap protects the smallest k; the root is always the next item to evict.
For nums = [3,2,1,5,6,4] and k = 2, push 3. The heap has room, so nothing is removed. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the root 5, rather than the largest retained value 6, the answer for k=2?
Sources and provenance
Full interview answer 13 min read
Return the value at a requested descending rank, counting repeated array entries separately.
Problem
Input. An integer list nums and a one-based integer rank k satisfying 1 <= k <= len(nums).
Output. Return the value in position k when all occurrences are ordered from largest to smallest.
Rules. Equal values occupy separate ranks. Return a value, not its original index or the k largest values.
Preserve the input. The reference raises ValueError for invalid ranks, including empty input.
Example. For [3, 2, 1, 5, 6, 4] and k = 2, return 5.
For [5, 5, 4] and k = 2, return 5, not the second distinct value 4.
Picture
Protect k places, with the weakest protected value easiest to remove.
After each input, the retained multiset contains the largest min(k, processed) occurrences seen.
Push the new occurrence; if there are too many, evict the minimum.
Removing the smallest of k+1 candidates leaves the best k.
After input
Retained heap values
Root threshold
3,2
[2,3]
2
3,2,1,5
[3,5]
3
3,2,1,5,6,4
[5,6]
5
Problem trace
The smallest of the largest k values is the kth largest
Read it this way:The heap keeps only the three largest values seen so far. Its root is the weakest survivor and sets the admission boundary for a new value. That root is the third-largest value, even when a smaller discarded value exists outside the heap. Why is the answer four rather than the smallest observed value two?
Reference drawing
Problem trace
The smallest of the largest k values is the kth largest
Execution trace
Input and goalFind the `k`th largest value in an unsorted array.
Seed the candidate heapFor nums = [3,2,1,5,6,4] and k = 2, push 3. The heap has room, so nothing is removed.
heap
3
input[3,2,1,5,6,4]current3processed1 of 6size1 <= k
input
[3,2,1,5,6,4]
current
3
processed
1 of 6
Fill the second slotPush 2. The min-heap orders the two protected candidates as [2,3], with the weaker candidate 2 at the root.
heap
2
3
current2processed2 of 6size2 = kactionkeep both
current
3→2
processed
1 of 6→2 of 6
size
1 <= k→2 = k
Discard an undersized candidatePush 1 to make [1,3,2]. Size 3 exceeds k, so pop root 1; [2,3] still holds the largest two of [3,2,1].
heap
2
3
current1processed3 of 6overflow[1,3,2]actionpop 1
current
2→1
processed
2 of 6→3 of 6
overflow
not shown→[1,3,2]
Raise the protected floorPush 5 to make [2,3,5], then pop 2. The retained candidates become [3,5], so the root threshold rises to 3.
heap
3
5
current5processed4 of 6overflow[2,3,5]actionpop 2
current
1→5
processed
3 of 6→4 of 6
overflow
[1,3,2]→[2,3,5]
Keep the next large valuePush 6 to make [3,5,6], then pop 3. The heap [5,6] is exactly the largest two values seen so far.
heap
5
6
current6processed5 of 6overflow[3,5,6]actionpop 3
current
5→6
processed
4 of 6→5 of 6
overflow
[2,3,5]→[3,5,6]
Reject the last weaker valuePush 4 to make [4,6,5], then pop 4. The protected set remains [5,6] after all six inputs.
heap
5
6
current4processed6 of 6overflow[4,6,5]actionpop 4
current
6→4
processed
5 of 6→6 of 6
overflow
[3,5,6]→[4,6,5]
Read the kth largestThe root is the smallest of the two retained values: min([5,6]) = 5, so the second largest is 5.
heap
5
6
k2arithmeticmin([5,6]) = 5result5
k
not shown→2
arithmetic
not shown→min([5,6]) = 5
result
not shown→5
Recognize it
Use it when an unsorted or streaming input asks for the kth largest item or the largest k items, while sorting every value would retain more order than the answer needs.
Keep true
After each input is pushed and any size-(k+1) overflow root is popped, the heap contains exactly the largest min(k, processed) values seen; its root is the weakest retained candidate.
Reuse it
For a bounded best-k set, choose the opposite heap polarity: a min-heap protects the largest k and a max-heap protects the smallest k; the root is always the next item to evict.
For nums = [3,2,1,5,6,4] and k = 2, push 3. The heap has room, so nothing is removed. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why is the root 5, rather than the largest retained value 6, the answer for k=2?
Read it this way:The heap keeps only the three largest values seen so far. Its root is the weakest survivor and sets the admission boundary for a new value. That root is the third-largest value, even when a smaller discarded value exists outside the heap. Why is the answer four rather than the smallest observed value two?
Heap order guarantees each parent is no larger than its children.
It does not sort every array position.
The root becomes the kth largest only after at least k values arrive.
Code
import heapqdef find_kth_largest(nums: list[int], k: int) -> int: if not 1 <= k <= len(nums): raise ValueError("k must name an item in nums") heap: list[int] = [] for num in nums: heapq.heappush(heap, num) if len(heap) > k: heapq.heappop(heap) return heap[0]
Time is O(nlog(k+1)); auxiliary heap space is O(k).
The heap briefly holds k+1 candidates before eviction.
Writing log(k+1) also covers k=1 without suggesting zero work.
The input list is not modified.
Failure Check
Evicting the largest retained value protects the wrong end of the ordering.
Silently deduplicating changes the requested rank: [5,5,4] would incorrectly return 4 for this contract.
Change the Rank
New task: Count distinct values only.
Picture and change: Deduplicate before using the retained reference.
Its range guard now applies to the distinct count.
Check:[5,5,4], rank 2, returns 4.
Rank 3 now raises ValueError.
The set and list add O(d) storage for d distinct values, plus expected linear hashing work.
Use when: The specification explicitly asks for a distinct-value rank.
Change to Prefix Answers
New task: Report the kth largest after every stream prefix.
Picture and change: Preserve the bounded heap across arrivals.
Return None until k occurrences exist.
Require a positive integer k; total stream length need not be known.
def running_kth(values, k): if k <= 0: raise ValueError("positive k required") heap, answer = [], [] for value in values: heapq.heappush(heap, value) if len(heap) > k: heapq.heappop(heap) answer.append(heap[0] if len(heap) == k else None) return answer
Check: The source stream returns [None,2,2,3,5,5].
Once defined, the threshold never decreases as more values arrive.
Keep the heapq import above.
Time is O(nlog(k+1)), retained state is O(k), and the returned history adds O(n) space.
Use when: Answers are required before the complete input arrives.
Transfer Check
Why use a min-heap when the requested rank is largest-first?
Answer
The root must expose the worst protected candidate for eviction.
The desired output direction does not determine the useful eviction direction.
Compare frequency ranking when priority comes from counts rather than raw values.