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 withkand the scores already recorded (possibly none).add(score)records a score and returns thek-th highest of all scores so far, counting repeats separately (in[7, 7, 3]the 2nd highest is7).
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.