← Whiteboard questions

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

Input k = 3, scores = [40, 10, 30], adds = [25, 50, 5, 35]
Output [25, 30, 30, 35]
Why the top three scores change like this: 25 replaces 10, 50 replaces 25, 5 changes nothing, and 35 replaces 30. The third highest is the smallest of the top three.
Input k = 2, scores = [8, 8], adds = [8, 1, 9]
Output [8, 8, 8]
Why equal scores count separately. Three scores of 8 make the second highest 8, and a later 9 pushes in above them.
Input k = 2, scores = [5, 1, 9, 7], adds = [3, 8]
Output [7, 8]
Why the start holds more than k scores. Only 9 and 7 matter, so 3 changes nothing and 8 pushes 7 out.

Constraints

Your answer must contain

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.

Related problems

More Heap / Priority Queue problems
Kth Largest Element in a Stream: walkthrough and solution