Streaming K-th Largest Element Tracker

Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen

Problem Statement

Implement a stateful order-statistic tracker KthLargest and its command-replay wrapper kth_largest_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]] to report the k-th highest value across an expanding sequence of integers.

Your tracker supports two operations:

  • KthLargest(k: int, nums: List[int]) — Initializes the tracker with target rank k and starting integers nums (which may be empty when k == 1).
  • add(val: int) -> int — Appends val to the multiset of observed numbers and returns the k-th highest integer across all values recorded so far (both nums and every val inserted up to and including this call).

Duplicate values occupy distinct ranks rather than collapsing: if all N numbers observed so far are arranged in ascending order v_0 <= v_1 <= ... <= v_{N-1}, the answer after add is v_{N - k}. Every add call is guaranteed to have N >= k.

The function kth_largest_stream(operations, arguments) processes paired entries (operations[i], arguments[i]) in order:

  • When operations[i] == "KthLargest", arguments[i] is [k, nums]; construct KthLargest(k, nums) and record None.
  • When operations[i] == "add", arguments[i] is [val]; invoke add(val) and record its integer result.

Examples

Example 1

Input:
  operations = ["KthLargest", "add", "add", "add", "add", "add"]
  arguments  = [[3, [6, 2, 9, 7]], [4], [7], [12], [10], [5]]
Output:
  [None, 6, 7, 7, 9, 9]

Walk-through: Starting with [6, 2, 9, 7] (k = 3), the top three numbers are {6, 7, 9}. - add(4) -> sorted [2, 4, 6, 7, 9], 3rd highest is 6. - add(7) -> sorted [2, 4, 6, 7, 7, 9], 3rd highest is 7. - add(12) -> sorted [2, 4, 6, 7, 7, 9, 12], 3rd highest is 7. - add(10) -> sorted [..., 7, 9, 10, 12], 3rd highest is 9. - add(5) -> 5 stays below {9, 10, 12}, 3rd highest remains 9.

Example 2

Input:
  operations = ["KthLargest", "add", "add", "add"]
  arguments  = [[1, []], [-8], [-4], [2]]
Output:
  [None, -8, -4, 2]

Walk-through: With k = 1 and an empty initial list, each add returns the running maximum: -8, then -4, then 2.

Example 3

Input:
  operations = ["KthLargest", "add", "add", "add"]
  arguments  = [[2, [5, 5]], [1], [5], [9]]
Output:
  [None, 5, 5, 5]

Walk-through: Equal copies count separately. After add(1) the sorted stream [1, 5, 5] has 2nd highest 5; after add(5) ([1, 5, 5, 5]) it is still 5; after add(9) ([1, 5, 5, 5, 9]) the top two are {5, 9}, so the 2nd highest remains 5.

Constraints

  • 1 <= k <= 10^4
  • k - 1 <= len(nums) <= 10^4 (so at least k values exist after every add call)
  • At most 10^4 "add" calls are performed
  • -2^31 <= nums[i], val <= 2^31 - 1

Step-by-step walkthrough

  1. Understand the streaming problem and judge format

    We need a tracker initialized with rank k (1 <= k <= 10^4) and starting numbers nums. Each call to add(val) appends val to the stream and returns the k-th highest number observed so far — counting duplicate copies separately:

    Seen so far: [6, 2, 9, 7, 7]  ->  sorted ascending: [2, 6, 7, 7, 9]
                                                               ^  ^  ^
                                                             3rd 2nd 1st highest
    For k = 3, the 3rd highest is 7 (each copy of 7 takes its own rank).
    

    The automated judge drives our class via two parallel lists, operations and arguments:

    Index i | operations[i] | arguments[i]       | Returned entry in results
    --------+---------------+--------------------+--------------------------
    0       | "KthLargest"  | [3, [6, 2, 9, 7]]  | None  (constructs object)
    1       | "add"         | [4]                | 6
    2       | "add"         | [7]                | 7
    

    The constraints guarantee at least k total values exist after every add call (so nums starts with at least k - 1 numbers).

  2. Why keeping and sorting every number wastes work

    A literal brute-force implementation appends every incoming val to a growing list values, sorts values, and returns values[-k]. With N numbers seen so far:

    • Re-sorting from scratch (sorted(values)) takes O(N log N) per add.
    • Keeping values sorted with binary search (bisect.insort) finds the insertion index in O(log N), but inserting into the middle of a Python list still shifts up to N elements in memory (O(N) per add).

    Look at what is wasted: once a number falls outside the k largest numbers seen so far, it can never become the k-th largest again! Adding more numbers to the stream can only push the k-th largest cutoff upward (or leave it tied), never downward.

  3. Key idea: store only the top k in a min-heap

    Imagine a VIP leaderboard with only k seats for the k largest numbers seen so far. Among those k VIPs inside, which one is the k-th largest overall? The smallest of the k VIPs!

    That is why we use a min-heap (not a max-heap) of size at most k. In Python's heapq, min_heap[0] always holds the smallest element in the heap in O(1) time:

    Top k = 3 VIPs currently in min_heap: {5, 8, 10}
    
            min_heap[0] = 5    <-- smallest of top 3 == 3rd largest overall!
                        /   \
                       8     10
    
    New val = 4 arrives:  4 <= 5 -> cannot beat the gatekeeper, discard in O(1)!
    New val = 9 arrives:  9 >  5 -> evict 5 and insert 9 in O(log k) -> new root is 8!
    

    Notice why a max-heap would be the wrong choice: a max-heap puts the 1st largest at index 0, hiding the k-th largest down at the bottom where finding or evicting it would take O(k) time instead of O(1) / O(log k).

  4. Code the KthLargest class

    Both __init__ and add funnel each number through a single helper _push_bounded(val):

    1. Heap has < k items: We don't have k numbers yet, so push val with heapq.heappush.
    2. Heap already has k items and val > self.min_heap[0]: val belongs in the top k, pushing out the old k-th largest self.min_heap[0]. Python's heapq.heapreplace(self.min_heap, val) pops the root and sifts val into place in one O(log k) operation (faster than calling heappop followed by heappush).
    3. Heap has k items and val <= self.min_heap[0]: Do nothing! Even in a tie (val == self.min_heap[0]), swapping one copy for an identical copy leaves the top-k multiset unchanged, so skipping saves an O(log k) heap update.
    class KthLargest:
        def __init__(self, k: int, nums: List[int]):
            self.k = k
            # min_heap: binary min-heap of at most k integers (the k largest seen so far);
            # min_heap[0] holds the smallest of those k values — i.e., the k-th largest overall.
            self.min_heap: List[int] = []
            for num in nums:
                self._push_bounded(num)
    
        def _push_bounded(self, val: int) -> None:
            # Case 1: Heap is not full yet (< k items) — keep val unconditionally.
            if len(self.min_heap) < self.k:
                heapq.heappush(self.min_heap, val)
            # Case 2: Heap holds k items — only a strictly larger val enters the top k
            # and evicts the old k-th largest at min_heap[0] in one O(log k) operation.
            elif val > self.min_heap[0]:
                heapq.heapreplace(self.min_heap, val)
    
        def add(self, val: int) -> Optional[int]:
            self._push_bounded(val)
            if len(self.min_heap) < self.k:
                return None
            return self.min_heap[0]
    
  5. Code the judge replay function

    kth_largest_stream loops over zip(operations, arguments), instantiating KthLargest when it sees "KthLargest" (appending None) and calling tracker.add(args[0]) when it sees "add":

    def kth_largest_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        results: List[Optional[int]] = []
        tracker: Optional[KthLargest] = None
    
        for op, args in zip(operations, arguments):
            if op == "KthLargest":
                tracker = KthLargest(args[0], args[1])
                results.append(None)
            elif op == "add":
                results.append(tracker.add(args[0]))
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    
  6. Trace Example 1 step by step

    Let's trace k = 3, nums = [6, 2, 9, 7] followed by add(4), add(7), add(12), add(10), add(5):

    Step          | Action on min_heap (capacity k = 3)          | Top-3 multiset | min_heap[0] | Output
    --------------+----------------------------------------------+----------------+-------------+-------
    init: 6, 2, 9 | len < 3 -> push 6, push 2, push 9            | {2, 6, 9}      | 2           |
    init: 7       | 7 > 2 is True  -> heapreplace evicts 2 -> 7  | {6, 7, 9}      | 6           | None
    add(4)        | 4 > 6 is False -> ignore 4                   | {6, 7, 9}      | 6           | 6
    add(7)        | 7 > 6 is True  -> heapreplace evicts 6 -> 7  | {7, 7, 9}      | 7           | 7
    add(12)       | 12 > 7 is True -> heapreplace evicts 7 -> 12 | {7, 9, 12}     | 7           | 7
    add(10)       | 10 > 7 is True -> heapreplace evicts 7 -> 10 | {9, 10, 12}    | 9           | 9
    add(5)        | 5 > 9 is False -> ignore 5                   | {9, 10, 12}    | 9           | 9
    

    That produces [None, 6, 7, 7, 9, 9], matching Example 1 while keeping at most 3 integers in memory at all times.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    import heapq
    
    
    class KthLargest:
        def __init__(self, k: int, nums: List[int]):
            self.k = k
            # min_heap: binary min-heap of at most k integers (the k largest seen so far);
            # min_heap[0] holds the smallest of those k values — i.e., the k-th largest overall.
            self.min_heap: List[int] = []
            for num in nums:
                self._push_bounded(num)
    
        def _push_bounded(self, val: int) -> None:
            # Case 1: Heap is not full yet (< k items) — keep val unconditionally.
            if len(self.min_heap) < self.k:
                heapq.heappush(self.min_heap, val)
            # Case 2: Heap holds k items — only a strictly larger val enters the top k
            # and evicts the old k-th largest at min_heap[0] in one O(log k) operation.
            # (When val == min_heap[0], the top-k multiset is unchanged, so skipping saves O(log k).)
            elif val > self.min_heap[0]:
                heapq.heapreplace(self.min_heap, val)
    
        def add(self, val: int) -> Optional[int]:
            self._push_bounded(val)
            # Defensive check in case fewer than k values exist (ruled out by the problem constraints).
            if len(self.min_heap) < self.k:
                return None
            return self.min_heap[0]
    
    
    def kth_largest_stream(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
        # Replay constructor and stream-addition commands in order for the automated judge.
        results: List[Optional[int]] = []
        tracker: Optional[KthLargest] = None
    
        for op, args in zip(operations, arguments):
            if op == "KthLargest":
                tracker = KthLargest(args[0], args[1])
                results.append(None)
            elif op == "add":
                results.append(tracker.add(args[0]))
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine running an exclusive leaderboard with exactly k trophies for the k highest numbers ever seen. Who holds the k-th trophy? The smallest score among those k trophy holders! If you put that lowest trophy holder right at the front door as the gatekeeper, every new number val only needs one quick check: if val cannot beat the gatekeeper (val <= gatekeeper), val can never win a trophy — now or in the future — so we throw val away immediately; if val > gatekeeper, val takes the gatekeeper's trophy and whichever of the k trophy holders is now smallest becomes the new gatekeeper. Data structures give us this exact gatekeeper via a min-heap (a binary tree packed into an array where every parent is <= its children, keeping the minimum element at index 0 for O(1) lookup and O(log k) replacement).

Why do simpler approaches fall short? Appending every stream value to a list and sorting on each add costs O(N log N) per call, and even maintaining a sorted list with binary search (bisect.insort) shifts up to N elements in memory (O(N) per call). Worse, keeping all N historical elements wastes space on numbers below the top k that can never become the k-th largest once k larger numbers exist. Bounding a min-heap to size k makes every add depend only on k (O(log k)), completely independent of how long the stream runs!

Here is a quick trace for k = 3 starting from nums = [6, 2, 9, 7]:

Initial build (keep top 3 in min_heap):
  push 6, push 2, push 9 -> min_heap holds {2, 6, 9}, gatekeeper min_heap[0] = 2
  see 7 -> 7 > 2 -> evict 2, insert 7 -> min_heap holds {6, 7, 9}, gatekeeper = 6

Stream calls:
  add(4):  4 <= 6 -> discarded!                      min_heap = {6, 7, 9}  -> returns 6
  add(7):  7 >  6 -> evict 6, insert 7               min_heap = {7, 7, 9}  -> returns 7
  add(12): 12 > 7 -> evict one 7, insert 12          min_heap = {7, 9, 12} -> returns 7

Complexity

Let n = len(nums) be the length of the initial list and m be the number of add calls.

  • Time: O(n log k) for __init__, O(log k) per add, and O((n + m) log k) overall. Every number in nums and every add(val) performs at most one heappush or heapreplace on a heap whose size never exceeds k (and O(1) work whenever val <= min_heap[0]).
  • Space: O(k) auxiliary space (plus O(m) for the judge's output list). self.min_heap stores at most k integers regardless of how large n or m grows.

Edge cases

  • k = 1 (running maximum): The min-heap holds just 1 element (min_heap[0]), updating whenever a strictly larger value arrives (Example 2).
  • Initial nums has k - 1 elements (including nums = [] when k = 1): __init__ pushes all k - 1 values without error, and the very first add(val) brings len(self.min_heap) to k and returns the minimum of all k values.
  • Initial nums much longer than k: Extra values smaller than the top k are discarded during __init__, so memory never spikes past k.
  • Duplicate values ([5, 5] then add(5)): Equal copies occupy separate slots in the top k ([5, 5] has 2nd largest 5, as in Example 3). When val == min_heap[0] on a full heap, skipping replacement keeps the exact same multiset of k values.
  • Monotonically non-decreasing answers: Because elements are never deleted from the stream, the returned k-th largest value can only stay the same or increase after each add.
  • 32-bit signed extremes (-2^31 to 2^31 - 1): Only < and > comparisons are performed (no addition or negation), avoiding integer overflow in fixed-width languages as well.

Common mistakes

  • Reaching for a max-heap instead of a min-heap: Hearing "k-th largest" tempts many candidates to build a max-heap of all N elements and pop k times per query (O(k log N) per add). Remember: to evict the smallest member of the top k, you want the minimum at the root — a min-heap of size k!
  • Forgetting to cap the heap at size k inside __init__: Calling heapq.heapify(nums) without popping down to k elements leaves min_heap[0] pointing at the global minimum (N-th largest) instead of the k-th largest.
  • Indexing min_heap[-1] or min_heap[k - 1]: A binary heap array is not fully sorted; only min_heap[0] is guaranteed to be the minimum element.
  • Deduplicating stream values: Using a set computes the k-th largest distinct value, failing inputs like k = 2, nums = [5, 5], add(1) where the answer must be 5, not 1.

Alternative approaches

  • heapify + pop excess in __init__: Copying nums, running heapq.heapify in O(n) time, and calling heappop n - k times takes O(n + max(0, n - k) log n) build time and O(n) temporary space. Feeding nums one by one through _push_bounded is simpler, reuses the exact add logic, and uses only O(k) memory even if nums is a huge iterator.
  • Quickselect per query: Quickselect (Hoare's partitioning algorithm that finds the k-th largest element of an unsorted array in O(N) average time) is optimal for a single static query, but repeating it on m stream additions costs O(m * N) time and O(N) space — far slower than O(log k) per add.

Follow-up questions

  • How would you maintain the k-th largest value over a sliding window where older elements expire? Once elements can leave the top k, elements previously outside the top k can get promoted! Maintain two heaps — a min-heap top_k for the k largest active elements and a max-heap rest for the remaining W - k active elements — paired with lazy deletion (recording expired values in a hash map counter and popping stale roots only when they surface to top_k[0] or rest[0]), keeping each slide O(log W).
  • What data structure would you choose if callers could pass a different rank k on each query? Because a bounded heap discards elements below the fixed k, you must retain all N elements in an order-statistics tree (a balanced binary search tree where every node stores the size of its subtree so you can walk directly to rank k in O(log N) time) or, in Python with third-party libraries, sortedcontainers.SortedList (O(log N) insert and O(log N) index lookup).
  • How can you compute the global k-th largest element when the stream is partitioned across many worker machines? Have each of the M worker machines maintain its own local min-heap of size k. Because any element not in a worker's local top k already has at least k elements >= it on that single worker alone, it can never be in the global top k; thus a coordinator only merges M * k numbers (O(M * k log k)) at query time regardless of total stream volume.

Follow-up questions

Similar questions

More Zillow interview questions

All 3 Zillow questions →