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 rankkand starting integersnums(which may be empty whenk == 1).add(val: int) -> int— Appendsvalto the multiset of observed numbers and returns thek-th highest integer across all values recorded so far (bothnumsand everyvalinserted 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]; constructKthLargest(k, nums)and recordNone. - When
operations[i] == "add",arguments[i]is[val]; invokeadd(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^4k - 1 <= len(nums) <= 10^4(so at leastkvalues exist after everyaddcall)- At most
10^4"add"calls are performed -2^31 <= nums[i], val <= 2^31 - 1
Step-by-step walkthrough
Understand the streaming problem and judge format
We need a tracker initialized with rank
k(1 <= k <= 10^4) and starting numbersnums. Each call toadd(val)appendsvalto the stream and returns thek-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,
operationsandarguments: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] | 7The constraints guarantee at least
ktotal values exist after everyaddcall (sonumsstarts with at leastk - 1numbers).Why keeping and sorting every number wastes work
A literal brute-force implementation appends every incoming
valto a growing listvalues, sortsvalues, and returnsvalues[-k]. WithNnumbers seen so far:- Re-sorting from scratch (
sorted(values)) takesO(N log N)peradd. - Keeping
valuessorted with binary search (bisect.insort) finds the insertion index inO(log N), but inserting into the middle of a Python list still shifts up toNelements in memory (O(N)peradd).
Look at what is wasted: once a number falls outside the
klargest numbers seen so far, it can never become the k-th largest again! Adding more numbers to the stream can only push thek-th largest cutoff upward (or leave it tied), never downward.- Re-sorting from scratch (
Key idea: store only the top k in a min-heap
Imagine a VIP leaderboard with only
kseats for theklargest numbers seen so far. Among thosekVIPs inside, which one is thek-th largest overall? The smallest of thekVIPs!That is why we use a min-heap (not a max-heap) of size at most
k. In Python'sheapq,min_heap[0]always holds the smallest element in the heap inO(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 index0, hiding thek-th largest down at the bottom where finding or evicting it would takeO(k)time instead ofO(1)/O(log k).Code the KthLargest class
Both
__init__andaddfunnel each number through a single helper_push_bounded(val):- Heap has
< kitems: We don't haveknumbers yet, so pushvalwithheapq.heappush. - Heap already has
kitems andval > self.min_heap[0]:valbelongs in the topk, pushing out the oldk-th largestself.min_heap[0]. Python'sheapq.heapreplace(self.min_heap, val)pops the root and siftsvalinto place in oneO(log k)operation (faster than callingheappopfollowed byheappush). - Heap has
kitems andval <= 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-kmultiset unchanged, so skipping saves anO(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]- Heap has
Code the judge replay function
kth_largest_streamloops overzip(operations, arguments), instantiatingKthLargestwhen it sees"KthLargest"(appendingNone) and callingtracker.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 resultsTrace Example 1 step by step
Let's trace
k = 3,nums = [6, 2, 9, 7]followed byadd(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 | 9That produces
[None, 6, 7, 7, 9, 9], matching Example 1 while keeping at most3integers in memory at all times.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)peradd, andO((n + m) log k)overall. Every number innumsand everyadd(val)performs at most oneheappushorheapreplaceon a heap whose size never exceedsk(andO(1)work wheneverval <= min_heap[0]). - Space:
O(k)auxiliary space (plusO(m)for the judge's output list).self.min_heapstores at mostkintegers regardless of how largenormgrows.
Edge cases
k = 1(running maximum): The min-heap holds just1element (min_heap[0]), updating whenever a strictly larger value arrives (Example 2).- Initial
numshask - 1elements (includingnums = []whenk = 1):__init__pushes allk - 1values without error, and the very firstadd(val)bringslen(self.min_heap)tokand returns the minimum of allkvalues. - Initial
numsmuch longer thank: Extra values smaller than the topkare discarded during__init__, so memory never spikes pastk. - Duplicate values (
[5, 5]thenadd(5)): Equal copies occupy separate slots in the topk([5, 5]has 2nd largest5, as in Example 3). Whenval == min_heap[0]on a full heap, skipping replacement keeps the exact same multiset ofkvalues. - 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 eachadd. - 32-bit signed extremes (
-2^31to2^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
Nelements and popktimes per query (O(k log N)peradd). Remember: to evict the smallest member of the topk, you want the minimum at the root — a min-heap of sizek! - Forgetting to cap the heap at size
kinside__init__: Callingheapq.heapify(nums)without popping down tokelements leavesmin_heap[0]pointing at the global minimum (N-th largest) instead of thek-th largest. - Indexing
min_heap[-1]ormin_heap[k - 1]: A binary heap array is not fully sorted; onlymin_heap[0]is guaranteed to be the minimum element. - Deduplicating stream values: Using a
setcomputes thek-th largest distinct value, failing inputs likek = 2, nums = [5, 5], add(1)where the answer must be5, not1.
Alternative approaches
heapify+ pop excess in__init__: Copyingnums, runningheapq.heapifyinO(n)time, and callingheappopn - ktimes takesO(n + max(0, n - k) log n)build time andO(n)temporary space. Feedingnumsone by one through_push_boundedis simpler, reuses the exactaddlogic, and uses onlyO(k)memory even ifnumsis a huge iterator.- Quickselect per query: Quickselect (Hoare's partitioning algorithm that finds the
k-th largest element of an unsorted array inO(N)average time) is optimal for a single static query, but repeating it onmstream additions costsO(m * N)time andO(N)space — far slower thanO(log k)peradd.
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 topkcan get promoted! Maintain two heaps — a min-heaptop_kfor theklargest active elements and a max-heaprestfor the remainingW - kactive elements — paired with lazy deletion (recording expired values in a hash map counter and popping stale roots only when they surface totop_k[0]orrest[0]), keeping each slideO(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 allNelements 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 rankkinO(log N)time) or, in Python with third-party libraries,sortedcontainers.SortedList(O(log N)insert andO(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
Mworker machines maintain its own local min-heap of sizek. Because any element not in a worker's local topkalready has at leastkelements>=it on that single worker alone, it can never be in the global topk; thus a coordinator only mergesM * knumbers (O(M * k log k)) at query time regardless of total stream volume.
Follow-up questions
- How would you maintain the k-th largest value over a sliding window where older elements expire?
- What data structure would you choose if callers could pass a different rank k on each query?
- How can you compute the global k-th largest element when the stream is partitioned across many worker machines?
Similar questions
- Percent-Delimited Template Placeholder Expander
- Root Causes and Mitigations of LLM Hallucinations
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance