progress

~/problems / Heaps / Heaps and priority queues

Kth Largest Element in a Stream

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

An arcade machine shows a "score to beat" banner: the k-th highest score recorded so far, refreshed after every new score.

Build a class ScoreBoard:

  • ScoreBoard(k, scores) starts with k and the scores already recorded (possibly none).
  • add(score) records a score and returns the k-th highest of all scores so far, counting repeats separately (in [7, 7, 3] the 2nd highest is 7).
board = ScoreBoard(3, [40, 10, 25, 55])
board.add(30)    # 30   (55, 40, 30, 25, 10)
board.add(5)     # 30
board.add(60)    # 40   (60, 55, 40, ...)
board.add(40)    # 40   (60, 55, 40, 40, ...)
board.add(70)    # 55

solo = ScoreBoard(1, [])
solo.add(-4)     # -4
solo.add(-9)     # -4

k, the starting list and the number of add calls are each up to 10^5. At least k scores exist whenever add returns.

⭐ Bonus: a speed test with 100,000 adds earns a star with O(log k) per add instead of re-sorting each time.

Show hint

Scores below the banner never matter again. Keep only the k best, with the smallest of them instantly available.

Topic: Heaps and priority queues. heapq: top-k, k-way merge, two heaps for a running median.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc