Skip to content
BytePatterns

Kth Largest in a Score Stream

EasyTwo Heaps & K-Way Merge#min-heap#top-k#data-stream~15m

Problem

A leaderboard shows the kth highest score seen so far. Build a class KthLargest(k, scores) that starts from a list of scores and has one method, add(score), which records a new score and returns the current kth largest score, counting duplicates. Every call to add happens when at least k scores have been recorded, including the new one.

Examples

Input:  k = 3, scores = [4, 5, 8, 2], then add 3, 5, 10, 9, 4
Output: [4, 5, 5, 8, 8]
Why:    after adding 3 the scores are 2 3 4 5 8 and the third largest is 4
Input:  k = 2, scores = [0], then add -1, 1, -2, -4, 3
Output: [-1, 0, 0, 0, 1]
Why:    the first add makes two scores, so the second largest is the smaller of them
Input:  k = 1, scores = [], then add -3, -2, -4, 0, 4
Output: [-3, -2, -2, 0, 4]
Why:    edge case, with k = 1 the answer is simply the maximum so far

Hints

0 / 3

Stuck on the idea rather than the code? Top K in a Stream covers it.