Kth Largest Element in a Stream
Return the k-th largest value as numbers stream in, like the k-th highest score on a leaderboard.
DSA, Easy, Heap / Priority Queue
Which structure or algorithm, and what does it cost.
Build a class Leaderboard. Leaderboard(k, scores) starts with the list scores. The method add(score) records one new score and returns the k-th highest score so far. Equal scores count separately, so two scores of 8 are the first and second highest. The example input gives k, the starting scores, and the values passed to add, in order. Return the list of what each add returned.
Examples
Constraints
- 1 <=
k<= 50,000. scoresholds at leastk- 1 values, so everyaddhas a k-th highest score to return.scoresandaddstogether hold at most 200,000 values.- Each score is a whole number between 0 and 1,000,000,000.
Your answer must contain
- The simple method and its cost; the heap method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(log k) time per add and O(k) memory.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
You only ever need one number: the k-th highest. Ask which scores can never be that number again.
Hint 2 the approach
Keep just the k highest scores seen so far, in a structure that gives the smallest of them at once.
Hint 3 the key step
Use a min-heap of size k. A new score enters only if it beats the root, and then the root leaves. The root is the answer.
Walkthrough
Full walkthrough brute force to best
Brute force
After every add, sort all scores from highest to lowest and read position k. One sort costs O(n log n) for n scores, and with 200,000 adds that is far too much work. Memory is O(n).
Best method
Only the k highest scores can be the answer, and the answer is the smallest of them. Keep those k scores in a min-heap, which gives its smallest value at once. If a new score is not higher than the root, it cannot be in the top k, so skip it. If it is higher, replace the root with it. Either way the root is now the k-th highest. Each add touches a heap of size k, so it costs O(log k). The constructor loads the starting scores with the same rule.
Hand trace
Run on k = 3, scores = [40, 10, 30], adds = [25, 50, 5, 35]. The starting heap holds the top three, [10, 30, 40], with root 10. Add 25: it beats 10, so 10 leaves. Heap [25, 30, 40], answer 25. Add 50: it beats 25, so 25 leaves. Heap [30, 40, 50], answer 30. Add 5: it does not beat 30, so it is skipped. Answer 30. Add 35: it beats 30, so 30 leaves. Heap [35, 40, 50], answer 35. The result is [25, 30, 30, 35].
Code
from heapq import heappush, heapreplace
class Leaderboard:
def __init__(self, k, scores):
self.k = k
self.heap = [] # min-heap holding the k highest scores
for s in scores:
self.add(s)
def add(self, score):
if len(self.heap) < self.k:
heappush(self.heap, score)
elif score > self.heap[0]:
heapreplace(self.heap, score)
return self.heap[0]Time and memory
O(log k) time per add, because the heap never holds more than k scores. Loading n starting scores costs O(n log k). O(k) memory for the heap.
Common mistakes
- Using a max-heap. Its root is the highest score, but the answer is the smallest of the top k.
- Letting the heap grow past k scores. Then the root is no longer the k-th highest.
- Dropping repeated scores with a set. Equal scores count separately, so with k = 2 and scores [8, 8] the answer is 8, not a missing value.