Running Leaderboard of the K Largest Readings
Heaps, Sorting & SearchAuto-graded · 23 test casesLast updated
Process paired operation and value lists, tracking the K largest integers seen so far and recording a descending snapshot after every operation, using a bounded min-heap.
Running Leaderboard of the K Largest Readings
A monitoring tool receives integer readings one at a time and must always be able to show the k largest readings received so far.
You are given an integer k and two lists of equal length, operations and values. They are processed pairwise: the i-th step uses operations[i] and values[i].
"add": the readingvalues[i]is added to the stream."get": no reading is added. The paired value is a placeholder and must be ignored.
After every step, whether it is an "add" or a "get", append a snapshot to the output. The snapshot is a list of the k largest readings received so far, sorted in descending order.
Rules:
- Duplicates are separate readings. For example, after adding
5and5withk = 2, the snapshot is[5, 5]. - If fewer than
kreadings have been received, the snapshot contains all of them (still in descending order). - If
k == 0, every snapshot is an empty list. - If
k < 0, raiseValueError. - If any operation is neither
"add"nor"get", raiseValueError. - If the two lists differ in length, process only as many steps as the shorter list provides.
Return the list of snapshots, one per processed step, in order.
Constraints
kis an integer (it may be zero or negative; negative is an error as described above).operationscontains strings; valid values are"add"and"get".valuescontains integers, which may be negative or repeated.- The number of steps can be large, so storing every reading is wasteful. Aim for memory that depends on
k, not on the stream length, beyond the output itself.
Examples
Example 1
Input: running_top_k(3, ['add', 'add', 'add', 'add', 'get', 'add', 'get'], [4, 1, 7, 3, 0, 9, 0])
Output: [[4], [4, 1], [7, 4, 1], [7, 4, 3], [7, 4, 3], [9, 7, 4], [9, 7, 4]]
Example 2
Input: running_top_k(2, ['add', 'add', 'add', 'get'], [-5, -2, -8, 0])
Output: [[-5], [-2, -5], [-2, -5], [-2, -5]]
Example 3
Input: running_top_k(0, ['add', 'add', 'get'], [5, 10, 0])
Output: [[], [], []]
Hints
Hint 1
Think about what you need to remember: only the k best readings so far. Anything that can never make the top k can be dropped.
Hint 2
Use a min-heap capped at size k. Its root is the smallest of the current top k, so it is the value a newcomer has to beat.
Hint 3
When the heap is full, replace the root only if the new value is strictly larger. Produce each snapshot by sorting a copy of the heap in descending order, and handle k = 0 and k < 0 up front.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a min-heap holding at most k values: the k largest readings seen so far. Its root is the smallest of those, so it acts as the threshold a new reading must beat.
For each step:
"add"withk > 0:- If the heap has fewer than
kitems, push the value. - Otherwise, if the value is strictly greater than the root, replace the root with it (
heapreplace). If not, discard the value.
- If the heap has fewer than
"get": change nothing.- Any other operation: raise
ValueError.
Then append sorted(heap, reverse=True) to the output. k < 0 is rejected immediately, and k == 0 never stores anything, so all snapshots are empty.
Why it is correct
Invariant: after any prefix of the stream, the heap contains exactly the min(k, n) largest readings of that prefix, as a multiset.
- While the heap is not full, every reading is kept, so it holds all readings seen.
- When it is full and the new value
xis greater than the root (the k-th largest), the new topkis the old topkwithout the root plusx, which is exactly whatheapreplacedoes. - When
xis less than or equal to the root,xdoes not improve the topk. Ifxequals the root, keeping either copy gives the same multiset, so the strict comparison is safe.
Readings are never removed from the stream, so the threshold can only rise. A rejected value can never become part of the top k later.
Complexity
Let n be the number of steps.
- Heap update per
add: O(log k). - Snapshot per step: O(k log k) for sorting.
- Total time: O(n * k log k), dominated by producing sorted snapshots.
- Working space: O(k), plus O(n * k) for the output.
Reference solution
import heapq
from typing import List
def running_top_k(k: int, operations: List[str], values: List[int]) -> List[List[int]]:
if k < 0:
raise ValueError("k must be nonnegative")
heap = [] # min-heap holding the k largest values seen so far
result = []
for op, value in zip(operations, values):
if op == "add":
if k > 0:
if len(heap) < k:
heapq.heappush(heap, value)
elif value > heap[0]:
heapq.heapreplace(heap, value)
elif op != "get":
raise ValueError("unknown operation")
result.append(sorted(heap, reverse=True))
return result