Skip to content
mlmentorship

Keep the best k values with the weakest retained value at the root

Evict the smallest retained occurrence on overflow, then change distinctness or report streaming thresholds.

Published · 13 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Keep the best k values with the weakest retained value at the root

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

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.
input[3,2,1,5,6,4]current3processed1 of 6size1 <= k
input
[3,2,1,5,6,4]
current
3
processed
1 of 6

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?
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 inputRetained heap valuesRoot 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

Worked example: the kth largest is the smallest value in the retained top-k heapThe 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.The heap root is the weakest retainedentry, not the weakest inputRetain 3; compare by value4792outRoot 4 is the third largest;discarded two is not.
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

Worked example: the kth largest is the smallest value in the retained top-k heapThe 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.The heap root is the weakest retainedentry, not the weakest inputRetain 3; compare by value4792outRoot 4 is the third largest;discarded two is not.
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.
input[3,2,1,5,6,4]current3processed1 of 6size1 <= k
input
[3,2,1,5,6,4]
current
3
processed
1 of 6

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 heapq

def 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 ; auxiliary heap space is . 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.

def kth_largest_distinct(nums, k):
   return find_kth_largest(list(set(nums)), k)

Check: [5,5,4], rank 2, returns 4. Rank 3 now raises ValueError. The set and list add storage for 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 , retained state is , and the returned history adds 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.