KatInterview

Running Leaderboard of the K Largest Readings

Heaps, Sorting & SearchAuto-graded · 23 test cases
MediumAuto-gradedHeaps, Sorting & Searchheapstreamingtop-k

Last 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 reading values[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 5 and 5 with k = 2, the snapshot is [5, 5].
  • If fewer than k readings 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, raise ValueError.
  • If any operation is neither "add" nor "get", raise ValueError.
  • 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

  • k is an integer (it may be zero or negative; negative is an error as described above).
  • operations contains strings; valid values are "add" and "get".
  • values contains 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.