~/problems / Heaps / Heaps and priority queues

Kth Largest Element in a Stream

easy ~15 min

An arcade machine shows a "score to beat" banner: the k-th highest score recorded so far. Scores keep arriving one at a time, and after each one the banner must be refreshed.

Build a class ScoreBoard:

  • ScoreBoard(k, scores) starts with the fixed number k and a list of scores already recorded (possibly empty).
  • add(score) records a new score and returns the k-th highest of all scores recorded so far, counting repeats separately (so 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

Constraints:

  • 1 <= k <= 10^5 and 0 <= len(scores) <= 10^5; scores are in [-10^9, 10^9].
  • Up to 10^5 calls to add. Whenever add is called, at least k scores exist once the new one is counted.
  • Sorting all scores on every call is far too slow at this size. Aim for O(log k) per add after an O(n log k) (or better) setup.
Show hint

Scores below the current banner can never matter again. Keep only the k best, arranged so the smallest of them is instantly available and can be swapped out cheaply.

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