Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have arrived.

Problem: Keep the k-th largest score of a live leaderboard with a size-k min-heap and log the k-th largest once at least k scores have arrived.
import heapq
def run(stream, k):
    h, out = [], []
    for x in stream:
        heapq.heappush(h, x)
        if len(h) > k: heapq.heappop(h)
        if len(h) == k: out.append(h[0])
    return out
print(run([5, 1, 9, 3, 7, 8], 3))
What is printed?
  1. A. [1, 3, 5, 8]
  2. B. [9, 9, 9, 9]
  3. C. [1, 3, 5, 7]
  4. D. [5, 5, 7, 8]

Correct answer: C. [1, 3, 5, 7]

After 5, 1, 9 the heap holds {1, 5, 9} with top 1. Adding 3 evicts 1 (top 3), adding 7 evicts 3 (top 5), adding 8 evicts 5 (top 7). The heap root is the smallest of the k largest, which is exactly the k-th largest.

More Coding Interview Problems questions

Exams that ask this topic