Top-K Frequencies Across Batch, Stream, and Sliding Windows
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
Implement frequency-ranked Top-K retrieval for integers across three operating modes: a fixed input list, a growing stream, and a bounded time window.
Across all three modes, rank candidate integers by descending occurrence count, breaking equal-count ties by ascending integer value (smaller integer first). Every query returns a list of at most k integers ordered from highest rank to lowest rank. When fewer than k distinct integers have positive counts, return all of them in rank order; when k <= 0 in the batch function (or k == 0 in the classes), return [].
- Mode 1 — Batch array (
top_k_frequent):top_k_frequent(nums: List[int], k: int) -> List[int]returns the topkintegers fromnums.
- Mode 2 — Unbounded stream (
StreamingTopK):StreamingTopK(k: int)initializes an empty stream tracker (k >= 0; raiseValueErrorifk < 0).add(x: int) -> Nonerecords one arrival of integerx.topk() -> List[int]returns the current topkintegers over all arrivals seen so far.
- Mode 3 — Sliding time window (
SlidingWindowTopK):SlidingWindowTopK(k: int, window: int = 3600)tracks arrivals within a trailingwindow-second span (k >= 0andwindow >= 0; raiseValueErrorif either is negative).add(t: int, x: int) -> Nonerecords integerxat integer secondt.topk(t: int) -> List[int]returns the topkintegers counting only arrivals whose timestamps lie in the closed interval[t - window, t](both endpoints included).- Timestamps passed to
addandtopknever move backward; if a call supplieststrictly less than the preceding call's timestamp, raiseValueError.
Examples
Example 1
Input:
nums = [8, 3, 8, 5, 3, 8, 5, 2]
k = 2
result = top_k_frequent(nums, k)
Output:
[8, 3]
Explanation:
The occurrence counts are 8 -> 3, 3 -> 2, 5 -> 2, and 2 -> 1. Integer 8 takes first place with count 3; 3 and 5 tie at count 2, so the smaller value 3 takes second place.
Example 2
Input:
stream = StreamingTopK(2)
stream.add(6)
r1 = stream.topk()
stream.add(4)
r2 = stream.topk()
stream.add(4)
r3 = stream.topk()
for _ in range(3):
stream.add(9)
r4 = stream.topk()
Output:
r1 = [6]
r2 = [4, 6]
r3 = [4, 6]
r4 = [9, 4]
Explanation:
After add(6), only one distinct integer exists ([6]). After the first add(4), 4 and 6 tie at count 1, placing 4 ahead of 6. A second add(4) raises 4 to count 2. Finally, three add(9) calls push 9 to count 3, moving [9, 4] ahead of 6 (count 1).
Example 3
Input:
tracker = SlidingWindowTopK(k=1, window=3600)
for _ in range(3):
tracker.add(10, 20)
for _ in range(2):
tracker.add(900, 30)
q1 = tracker.topk(3610)
q2 = tracker.topk(3611)
tracker.add(4000, 20)
q3 = tracker.topk(4501)
Output:
q1 = [20]
q2 = [30]
q3 = [20]
Explanation:
At t = 3610, the active interval [10, 3610] still includes the three arrivals of 20 at t = 10 (20 -> 3 beats 30 -> 2). One second later at t = 3611, [11, 3611] drops all three t = 10 arrivals, promoting 30 (count = 2). Adding 20 at t = 4000 gives 20 -> 1, and querying at t = 4501 ([901, 4501]) expires both t = 900 arrivals of 30, leaving [20].
Constraints
0 <= len(nums) <= 2 * 10^5intop_k_frequent.- Up to
2 * 10^5totaladdandtopkcalls onStreamingTopKorSlidingWindowTopK. - Input integers can be negative, zero, or positive, and duplicates may be frequent or bursty at identical timestamps.
StreamingTopKandSlidingWindowTopKrequirek >= 0(andwindow >= 0), raisingValueErrorotherwise;SlidingWindowTopKraisesValueErrorwhenever timestamptdecreases relative to the prior call.
Step-by-step walkthrough
Understand the three variants and the tie-break rule
All three variants ask for the
kmost frequent integers, first on a fixed list, then on an unending stream, and finally inside a moving 1-hour (3600-second) time window.Before writing code, we pin down the exact rules where the prompt asks us to clarify:
- Deterministic tie-breaking: higher frequency count comes first; if two integers have the exact same count, the smaller integer comes first. Giving every pair of values a strict winner makes every output unique and easy to test.
- Short results: if fewer than
kdistinct values have positive counts, return all of them (best first). Ifk <= 0, return[]. - Inclusive window: in Variant 3, a query at timestamp
tincludes every event whose timestampssatisfiest - 3600 <= s <= t(both endpoints included). Because timestamps are monotonic non-decreasing across calls, passing a timestamp smaller than the previous call raisesValueError.
The public API we implement across the three variants is:
def top_k_frequent(nums: List[int], k: int) -> List[int]: ... class StreamingTopK: def __init__(self, k: int) -> None: ... def add(self, x: int) -> None: ... def topk(self) -> List[int]: ... class SlidingWindowTopK: def __init__(self, k: int, window: int = 3600) -> None: ... def add(self, t: int, x: int) -> None: ... def topk(self, t: int) -> List[int]: ...Variant 1: count frequencies and keep K with a heap
For a static array
numsof lengthn, we first count how often each distinct integer appears using a hash map (Counter(nums)), which takes oneO(n)pass. Supposeddistinct values appear (d <= n).To select the best
kout of thoseddistinct values without sorting allditems whenkis small, we pair each value with the rank tuple(-count, value):- Python compares tuples left-to-right.
- Negating
countmakes a higher frequency look smaller (-3 < -2), while leavingvaluepositive makes a smaller integer win ties ((-2, 2) < (-2, 4)). heapq.nsmallest(k, ranked_candidates)maintains a heap of onlykitems inO(d log k)time and returns thosektuples sorted best-first.
Trace Example 1 on
nums = [8, 3, 8, 5, 3, 8, 5, 2]withk = 2:counts: {8: 3, 3: 2, 5: 2, 2: 1} ranked_candidates: [(-3, 8), (-2, 3), (-2, 5), (-1, 2)] sorted tuple order: (-3, 8) < (-2, 3) < (-2, 5) < (-1, 2) nsmallest(2, ...): [(-3, 8), (-2, 3)] -> result = [8, 3]def top_k_frequent(nums: List[int], k: int) -> List[int]: """Variant 1: return the k most frequent values of nums, ordered best first.""" if k <= 0: return [] # Phase 1: count how many times each distinct integer appears in O(n) time. counts = Counter(nums) # Phase 2: build (-count, value) rank tuples so Python's min-heap treats # higher counts and smaller tie-break values as "smaller" (better) keys. ranked_candidates: List[Tuple[int, int]] = [] for value, count in counts.items(): ranked_candidates.append((-count, value)) # heapq.nsmallest maintains a bounded buffer of size k in O(d log k) time # and returns the k smallest tuples already sorted best-first. best_tuples = heapq.nsmallest(k, ranked_candidates) result: List[int] = [] for _, value in best_tuples: result.append(value) return resultWhy Variants 2 and 3 cannot re-sort on every query
A tempting shortcut for streaming is to update
counts[x] += 1inO(1)insideadd(x)and run Variant 1'sheapq.nsmallestinsidetopk(). That works if queries are rare, but fails when queries are frequent:- Suppose
200,000operations alternate betweenadd(new_value)andtopk(). - The
i-th query scansidistinct entries incounts. - Across
100,000queries, total work is1 + 2 + ... + 100,000 ≈ 5 * 10^9operations — far too slow.
Notice what actually happens during a single
+1(new arrival) or-1(window expiry) update: only one integer's count changes by 1, while every other integer keeps its exact rank. Therefore, the set of top-kwinners can change by at most one item:- If fewer than
klive items are in the top set (or a top item's count just fell to0), the single best outsider steps into the empty spot. - If an outsider's count grew (or a top item's count shrank) so that the best outsider now beats the worst top item, those two items swap places.
So we only ever need fast access to the two items sitting right on the
k-th boundary: the worst item inside Top-K and the best item outside Top-K.- Suppose
Split live values across two heaps with lazy deletion
We build one reusable
TopKCounterthat supports bothincrement(value)anddecrement(value). It splits all live values (count > 0) into two groups:Top-K winners (set `in_top`, size <= k) Challengers (`rest`, all other live values) +---------------------------------------+ +------------------------------------------+ | best ... worst_of_top | <--> | best_of_rest ... worst | | top_heap stores (count, -value) | swap | rest_heap stores (-count, value) | +---------------------------------------+ +------------------------------------------+Look closely at the signs in the two min-heaps (
heapqalways puts the smallest tuple at index0):rest_heapstores(-count, value): higher count gives a more negative first number, and smallervaluewins ties, sorest_heap[0]is the best outsider.top_heapstores(count, -value): exact opposite signs! Lowercountcomes first, and largervalue(-valueis more negative) comes first on ties, sotop_heap[0]is the worst member ofin_top.
Python's
heapqcannot update or delete an element buried in the middle of a heap. Instead, we use lazy deletion: every time a value's count or side changes, we push a brand-new tuple and leave old tuples alone. Whenever we inspecttop_heap[0]orrest_heap[0], we verify that the value still belongs to that side and its stored count still equalsself.counts[value]. If not, the tuple is outdated ("stale"), so we pop and discard it.class TopKCounter: def __init__(self, k: int) -> None: if k < 0: raise ValueError("k must be non-negative") self.k = k # counts: maps each live value -> current positive frequency, e.g. {7: 3, 8: 2}. self.counts: Dict[int, int] = {} # in_top: set of at most k values currently ranked in the top-K group. self.in_top: Set[int] = set() # top_heap: min-heap of (count, -value) for in_top items; root is the WORST top item # (lowest count, and largest value among ties). self.top_heap: List[Tuple[int, int]] = [] # rest_heap: min-heap of (-count, value) for non-top items; root is the BEST outsider # (highest count, and smallest value among ties). self.rest_heap: List[Tuple[int, int]] = [] def _worst_of_top(self) -> Optional[int]: """Return the lowest-ranked live item in in_top, popping stale heap roots first.""" while self.top_heap: count, neg_value = self.top_heap[0] value = -neg_value if value in self.in_top and self.counts.get(value) == count: return value heapq.heappop(self.top_heap) return None def _best_of_rest(self) -> Optional[int]: """Return the highest-ranked live item outside in_top, popping stale heap roots first.""" while self.rest_heap: neg_count, value = self.rest_heap[0] expected_count = -neg_count if value not in self.in_top and self.counts.get(value) == expected_count: return value heapq.heappop(self.rest_heap) return None def _move_to_top(self, value: int) -> None: self.in_top.add(value) heapq.heappush(self.top_heap, (self.counts[value], -value)) def _move_to_rest(self, value: int) -> None: self.in_top.discard(value) heapq.heappush(self.rest_heap, (-self.counts[value], value))Update counts, rebalance the boundary, and compact stale entries
Now we write
_change(value, delta)and_rebalance():- Update
counts: ifnew_count == 0, deletevaluefromcountsandin_top(any old tuples in the heaps are now automatically recognized as stale). Otherwise storenew_countand push a fresh tuple ontotop_heap(ifvalue in self.in_top) orrest_heap. - Rebalance: first fill
in_topup to sizekfromrest_heapif room exists, then check whetherbest_reststrictly beatsworst_topby comparing their rank tuples(-count, value). If so, pop both roots and swap their groups. - Prevent stale buildup (
_compact): in a long sliding-window run, stale entries deep inside a heap might sit unpopped whiled(the number of live distinct values) stays small. Wheneverlen(top_heap) + len(rest_heap) > 2 * d + 16, we rebuild both heaps fromself.countsusingheapq.heapifyinO(d)time. Because> 2d + 16entries shrink down todlive entries, every rebuild destroys more thand + 16stale entries that were each pushed once — so rebuilds add onlyO(1)amortized work per heap push.
Finally,
topk()only sorts the<= kitems insideself.in_top, takingO(k log k)time regardless of how largedgrows.def increment(self, value: int) -> None: self._change(value, 1) def decrement(self, value: int) -> None: self._change(value, -1) def topk(self) -> List[int]: # Sort only the <= k members of in_top by (-count, value) in O(k log k) time. ranked_top: List[Tuple[int, int]] = [] for value in self.in_top: ranked_top.append((-self.counts[value], value)) ranked_top.sort() result: List[int] = [] for _, value in ranked_top: result.append(value) return result def _change(self, value: int, delta: int) -> None: new_count = self.counts.get(value, 0) + delta if new_count < 0: raise ValueError(f"count of {value} would become negative") if new_count == 0: # Removing the value from counts and in_top automatically invalidates # all of its old tuples still sitting inside top_heap or rest_heap. del self.counts[value] self.in_top.discard(value) else: self.counts[value] = new_count # Push an updated snapshot onto whichever heap currently owns this value. if value in self.in_top: heapq.heappush(self.top_heap, (new_count, -value)) else: heapq.heappush(self.rest_heap, (-new_count, value)) # Restore the partition invariant across the k-th boundary. self._rebalance() # Compact both heaps when stale entries exceed live items by more than d + 16, # bounding heap size to O(d) while keeping rebuild cost O(1) amortized per update. total_heap_entries = len(self.top_heap) + len(self.rest_heap) if total_heap_entries > 2 * len(self.counts) + 16: self._compact() def _rebalance(self) -> None: # Phase 1: if in_top has fewer than k items (e.g. startup or an in_top item hit count 0), # promote the best available item from rest_heap. while len(self.in_top) < self.k: best_rest = self._best_of_rest() if best_rest is None: break heapq.heappop(self.rest_heap) self._move_to_top(best_rest) # Phase 2: while the best outsider strictly beats the worst insider, swap them. # Because only one item's count changed, at most one swap occurs per _change call. while True: best_rest = self._best_of_rest() worst_top = self._worst_of_top() if best_rest is None or worst_top is None: return best_rest_rank = (-self.counts[best_rest], best_rest) worst_top_rank = (-self.counts[worst_top], worst_top) # Smaller rank tuple means higher priority; stop when best_rest cannot beat worst_top. if best_rest_rank >= worst_top_rank: return heapq.heappop(self.rest_heap) heapq.heappop(self.top_heap) self._move_to_top(best_rest) self._move_to_rest(worst_top) def _compact(self) -> None: """Rebuild both heaps from live counts in O(d) time so stale tuples never pile up.""" self.top_heap = [] self.rest_heap = [] for value, count in self.counts.items(): if value in self.in_top: self.top_heap.append((count, -value)) else: self.rest_heap.append((-count, value)) heapq.heapify(self.top_heap) heapq.heapify(self.rest_heap)- Update
Wrap the counter for unbounded streams and sliding windows
With
TopKCounterready, Variants 2 and 3 become small, clean wrappers:StreamingTopK(Variant 2): delegatesadd(x)tocounter.increment(x)andtopk()tocounter.topk().SlidingWindowTopK(Variant 3): keeps acollections.dequeof(timestamp, value)pairs in arrival order. Because timestamps never decrease, the oldest un-expired event is always atevents[0]. Bothadd(t, x)andtopk(t)call_advance(t)first to pop events strictly older thant - window(timestamp < t - window, keepingt - windowitself inside the window) and decrement their counts.
Trace Example 3 on
SlidingWindowTopK(k=1, window=3600)when20arrives three times att = 10and30arrives twice att = 900:Call Active window Deque after _advance Counts in_top / rest Output --------------- -------------- -------------------------------------- -------------- -------------- ------ add(10, 20) x3 [-3590, 10] [(10,20),(10,20),(10,20)] {20: 3} {20} / {} - add(900, 30) x2 [-2700, 900] [(10,20)x3, (900,30),(900,30)] {20: 3, 30: 2} {20} / {30} - topk(3610) [10, 3610] same (10 < 10 is False, kept!) {20: 3, 30: 2} {20} / {30} [20] topk(3611) [11, 3611] [(900,30),(900,30)] (three 20s pop) {30: 2} {30} / {} [30] add(4000, 20) [400, 4000] [(900,30),(900,30),(4000,20)] {30: 2, 20: 1} {30} / {20} - topk(4501) [901, 4501] [(4000,20)] (both 30s at 900 pop) {20: 1} {20} / {} [20]Notice why
topk(3611)needsrest_heap: as20decrements3 -> 2 -> 1 -> 0,30was waiting outsidein_topand gets promoted automatically.class StreamingTopK: """Variant 2: Top-K over an unbounded stream where counts only increase.""" def __init__(self, k: int) -> None: self.counter = TopKCounter(k) def add(self, x: int) -> None: self.counter.increment(x) def topk(self) -> List[int]: return self.counter.topk() class SlidingWindowTopK: """Variant 3: Top-K over events whose timestamps lie in [t - window, t] inclusive.""" def __init__(self, k: int, window: int = 3600) -> None: if window < 0: raise ValueError("window must be non-negative") self.counter = TopKCounter(k) self.window = window # events: FIFO deque of (timestamp, value) ordered from oldest (left) to newest (right). self.events: Deque[Tuple[int, int]] = deque() self.last_time: Optional[int] = None def _advance(self, t: int) -> None: # Reject out-of-order timestamps because FIFO expiry relies on non-decreasing time. if self.last_time is not None and t < self.last_time: raise ValueError("timestamps must be non-decreasing") self.last_time = t # Strict '<' keeps events at exactly t - window inside [t - window, t]. cutoff = t - self.window while self.events and self.events[0][0] < cutoff: _, expired_value = self.events.popleft() self.counter.decrement(expired_value) def add(self, t: int, x: int) -> None: self._advance(t) self.events.append((t, x)) self.counter.increment(x) def topk(self, t: int) -> List[int]: # Advance first so queries after a quiet period still evict expired events. self._advance(t) return self.counter.topk()Complete solution
from typing import Deque, Dict, List, Optional, Set, Tuple from collections import Counter, deque import heapq # Ranking rule used across all three variants: # 1. Higher frequency count comes first. # 2. Equal counts break ties by putting the smaller integer value first. def top_k_frequent(nums: List[int], k: int) -> List[int]: """Variant 1: return the k most frequent values of nums, ordered best first.""" if k <= 0: return [] # Phase 1: count how many times each distinct integer appears in O(n) time. counts = Counter(nums) # Phase 2: build (-count, value) rank tuples so Python's min-heap treats # higher counts and smaller tie-break values as "smaller" (better) keys. ranked_candidates: List[Tuple[int, int]] = [] for value, count in counts.items(): ranked_candidates.append((-count, value)) # heapq.nsmallest maintains a bounded buffer of size k in O(d log k) time # and returns the k smallest tuples already sorted best-first. best_tuples = heapq.nsmallest(k, ranked_candidates) result: List[int] = [] for _, value in best_tuples: result.append(value) return result class TopKCounter: """Maintain dynamic item counts (+1 / -1) while tracking the top k items. Live items (count > 0) are partitioned into two disjoint groups: - in_top: up to k best items currently in the top-K answer. - rest: all other items with count > 0. Because Python's heapq cannot update or delete entries in the middle of a heap, every count or group change pushes a fresh tuple and leaves older tuples to be discarded lazily when they reach a heap root. """ def __init__(self, k: int) -> None: if k < 0: raise ValueError("k must be non-negative") self.k = k # counts: maps each live value -> current positive frequency, e.g. {7: 3, 8: 2}. self.counts: Dict[int, int] = {} # in_top: set of at most k values currently ranked in the top-K group. self.in_top: Set[int] = set() # top_heap: min-heap of (count, -value) for in_top items; root is the WORST top item # (lowest count, and largest value among ties). self.top_heap: List[Tuple[int, int]] = [] # rest_heap: min-heap of (-count, value) for non-top items; root is the BEST outsider # (highest count, and smallest value among ties). self.rest_heap: List[Tuple[int, int]] = [] def increment(self, value: int) -> None: self._change(value, 1) def decrement(self, value: int) -> None: self._change(value, -1) def topk(self) -> List[int]: # Sort only the <= k members of in_top by (-count, value) in O(k log k) time. ranked_top: List[Tuple[int, int]] = [] for value in self.in_top: ranked_top.append((-self.counts[value], value)) ranked_top.sort() result: List[int] = [] for _, value in ranked_top: result.append(value) return result def _change(self, value: int, delta: int) -> None: new_count = self.counts.get(value, 0) + delta if new_count < 0: raise ValueError(f"count of {value} would become negative") if new_count == 0: # Removing the value from counts and in_top automatically invalidates # all of its old tuples still sitting inside top_heap or rest_heap. del self.counts[value] self.in_top.discard(value) else: self.counts[value] = new_count # Push an updated snapshot onto whichever heap currently owns this value. if value in self.in_top: heapq.heappush(self.top_heap, (new_count, -value)) else: heapq.heappush(self.rest_heap, (-new_count, value)) # Restore the partition invariant across the k-th boundary. self._rebalance() # Compact both heaps when stale entries exceed live items by more than d + 16, # bounding heap size to O(d) while keeping rebuild cost O(1) amortized per update. total_heap_entries = len(self.top_heap) + len(self.rest_heap) if total_heap_entries > 2 * len(self.counts) + 16: self._compact() def _worst_of_top(self) -> Optional[int]: """Return the lowest-ranked live item in in_top, popping stale heap roots first.""" while self.top_heap: count, neg_value = self.top_heap[0] value = -neg_value if value in self.in_top and self.counts.get(value) == count: return value heapq.heappop(self.top_heap) return None def _best_of_rest(self) -> Optional[int]: """Return the highest-ranked live item outside in_top, popping stale heap roots first.""" while self.rest_heap: neg_count, value = self.rest_heap[0] expected_count = -neg_count if value not in self.in_top and self.counts.get(value) == expected_count: return value heapq.heappop(self.rest_heap) return None def _move_to_top(self, value: int) -> None: self.in_top.add(value) heapq.heappush(self.top_heap, (self.counts[value], -value)) def _move_to_rest(self, value: int) -> None: self.in_top.discard(value) heapq.heappush(self.rest_heap, (-self.counts[value], value)) def _rebalance(self) -> None: # Phase 1: if in_top has fewer than k items (e.g. startup or an in_top item hit count 0), # promote the best available item from rest_heap. while len(self.in_top) < self.k: best_rest = self._best_of_rest() if best_rest is None: break heapq.heappop(self.rest_heap) self._move_to_top(best_rest) # Phase 2: while the best outsider strictly beats the worst insider, swap them. # Because only one item's count changed, at most one swap occurs per _change call. while True: best_rest = self._best_of_rest() worst_top = self._worst_of_top() if best_rest is None or worst_top is None: return best_rest_rank = (-self.counts[best_rest], best_rest) worst_top_rank = (-self.counts[worst_top], worst_top) # Smaller rank tuple means higher priority; stop when best_rest cannot beat worst_top. if best_rest_rank >= worst_top_rank: return heapq.heappop(self.rest_heap) heapq.heappop(self.top_heap) self._move_to_top(best_rest) self._move_to_rest(worst_top) def _compact(self) -> None: """Rebuild both heaps from live counts in O(d) time so stale tuples never pile up.""" self.top_heap = [] self.rest_heap = [] for value, count in self.counts.items(): if value in self.in_top: self.top_heap.append((count, -value)) else: self.rest_heap.append((-count, value)) heapq.heapify(self.top_heap) heapq.heapify(self.rest_heap) class StreamingTopK: """Variant 2: Top-K over an unbounded stream where counts only increase.""" def __init__(self, k: int) -> None: self.counter = TopKCounter(k) def add(self, x: int) -> None: self.counter.increment(x) def topk(self) -> List[int]: return self.counter.topk() class SlidingWindowTopK: """Variant 3: Top-K over events whose timestamps lie in [t - window, t] inclusive.""" def __init__(self, k: int, window: int = 3600) -> None: if window < 0: raise ValueError("window must be non-negative") self.counter = TopKCounter(k) self.window = window # events: FIFO deque of (timestamp, value) ordered from oldest (left) to newest (right). self.events: Deque[Tuple[int, int]] = deque() self.last_time: Optional[int] = None def _advance(self, t: int) -> None: # Reject out-of-order timestamps because FIFO expiry relies on non-decreasing time. if self.last_time is not None and t < self.last_time: raise ValueError("timestamps must be non-decreasing") self.last_time = t # Strict '<' keeps events at exactly t - window inside [t - window, t]. cutoff = t - self.window while self.events and self.events[0][0] < cutoff: _, expired_value = self.events.popleft() self.counter.decrement(expired_value) def add(self, t: int, x: int) -> None: self._advance(t) self.events.append((t, x)) self.counter.increment(x) def topk(self, t: int) -> List[int]: # Advance first so queries after a quiet period still evict expired events. self._advance(t) return self.counter.topk()✅ Submit now — all tests should pass.
Intuition & how it works
Imagine running a live leaderboard for the k most-played songs. In a one-shot report (Mode 1), you simply tally every song's play count in a dictionary and use a min-heap (a tree-based priority queue that always keeps its smallest element at the top in logarithmic time) of size k to pick the winners. In a live stream (Modes 2 and 3), imagine dividing all songs into a "VIP room" holding the current Top k and a "waiting room" holding every other song: you only need one guard watching the weakest VIP (top_heap) and one guard watching the strongest challenger in the waiting room (rest_heap). Whenever a song gains or loses a play, at most one swap happens across that doorway; for the trailing sliding window (a moving time interval [t - window, t] that drops old events as time advances), a deque (a double-ended queue that appends to the right and pops from the left in O(1) time) remembers events in chronological order so expired plays can be subtracted one by one.
The naive streaming approach updates a dictionary in O(1) on add and re-runs the static O(d log k) selection over all d distinct values on every topk() call. When 200,000 operations alternate between adding a new value and querying topk(), those repeated full scans add up to roughly 5 * 10^9 steps and time out. Keeping just a single size-k heap also falls short in Mode 3: when a leader's old events expire and its count drops, a single heap has no record of which outside value has the highest count to replace it.
Walk through k = 2 (higher count first, smaller value breaks ties) on add(6), add(4), add(4), and three add(9) calls (Example 2):
add(6)-> counts{6: 1}, VIPin_top = {6},rest = {},topk()is[6].add(4)-> counts{6: 1, 4: 1}, VIP has room soin_top = {4, 6},topk()is[4, 6](4beats6on the tie).add(4)-> counts{4: 2, 6: 1},in_top = {4, 6},topk()is[4, 6].- First
add(9)-> counts{4: 2, 6: 1, 9: 1};9entersrest, and its rank(-1, 9)does not beat weakest VIP6with rank(-1, 6), soin_topstays{4, 6}. - Second
add(9)-> counts{4: 2, 9: 2, 6: 1}; challenger9now has rank(-2, 9), beating weakest VIP6((-1, 6)), so9and6swap ->in_top = {4, 9},rest = {6}. - Third
add(9)-> counts{9: 3, 4: 2, 6: 1},in_top = {9, 4},topk()returns[9, 4].
Because Python's heapq cannot edit an item's count in the middle of a heap, we use lazy deletion (pushing a fresh heap entry on every change and ignoring outdated entries later when they reach the top of a heap), plus periodic heap rebuilds so stale entries never accumulate.
Complexity
Let n be the input array length (Mode 1), d be the number of distinct values currently having a positive count, k be the requested output size, and W be the number of events currently inside the sliding window.
- Mode 1 time —
O(n + d log k): we scan allnintegers once to build the frequency map (O(n)), then pass thed(count, value)pairs throughheapq.nsmallest(k, ...), which maintains a heap of size at mostk(O(d log k), orO(d log d)whenk >= d). - Mode 1 space —
O(d): theCounterdictionary and the candidate tuple list each hold one entry per distinct integer. - Modes 2 & 3 update time (
increment/decrement) —O(log d)amortized: amortized time is the guaranteed average cost per operation over any sequence of operations, even if an occasional cleanup step does extra work. Each+1or-1change pushes at most a constant number of heap tuples (O(log d)each) and performs at most one boundary fill or swap. Every stale tuple is popped at most once (O(log d)). When total heap entries exceed2d + 16,_compactrebuilds both heaps inO(d)time; because shrinking> 2d + 16entries down todlive entries destroys more thand + 16stale entries that were each pushed once, rebuilds add onlyO(1)amortized work per push. In Mode 3, each event enters the deque once onaddand leaves once on expiry, so bothaddand expiry costO(log d)amortized per event. - Modes 2 & 3 query time (
topk) —O(k log k)(plus expiring old events in Mode 3):topkonly sorts the<= kintegers currently stored inin_top, completely independent ofd. - Modes 2 & 3 space —
O(d)for Mode 2,O(d + W)for Mode 3: compaction caps both heaps at roughly2d + 16entries alongside theO(d)dictionary and set, while Mode 3 also stores theWactive(timestamp, value)events in its deque.
Edge cases
- Fewer than
kdistinct values ork <= 0: when fewer thankdistinct values exist,in_topholds all of them (top_k_frequent([12, 12, 19], 5)returns[12, 19]). Whenk <= 0,top_k_frequentreturns[](andk == 0on the classes returns[]). - Exact frequency ties: ties are broken consistently by smaller integer value in
top_heap(using-value), inrest_heap(using+value), and intopk(). Withk = 1, callingadd(8)thenadd(2)immediately flipstopk()from[8]to[2]. - Negative numbers and zero: negating
valueinsidetop_heapreverses order cleanly for negative, zero, and positive integers alike (-(-7) = 7 > -(-4) = 4, so-7beats-4on ties). - Many distinct values with frequent queries:
topk()sorts at mostkitems rather than scanningditems, staying fast even when30,000distinct values are queried after everyadd. - Inclusive window boundary
[t - 3600, t]: in Example 3, an event at timestamp10is still valid att = 3610(10 < 3610 - 3600isFalse) and expires att = 3611(10 < 11isTrue). - Queries after a long silence: calling
topk(t)runs_advance(t)before readingin_top, so querying more than an hour after the lastaddproperly returns[]. - Out-of-order timestamps: if
t < last_timeon eitheraddortopk,_advanceraisesValueErrorrather than corrupting the chronological order of the deque.
Common mistakes
- Using
Counter.most_common(k)without handling ties:most_commonbreaks equal-count ties by first-seen insertion order rather than a value rule. Always state your tie-break rule and encode it explicitly. - Recomputing Top-K from
countsinsidetopk(): scanning allddistinct keys on every query turnsQqueries intoO(Q * d log k)work, which times out when queries are frequent. - Keeping only a single min-heap of size
kin Mode 3: when an item inside Top-K loses occurrences to window expiry, a single heap does not know which outside item has the highest count to replace it. - Mutating counts without lazy deletion or heap updates: changing
counts[x]does not automatically re-heapify old tuples inheapq. You must push a fresh tuple and verify counts when reading heap roots. - Using
<=instead of<when expiring events: popping whiletimestamp <= t - windowwrongly drops events at exact timestampt - window, which belong inside[t - window, t]. - Expiring events only inside
add(t, x): if no new events arrive for two hours,topk(t)would return stale leaders from hours ago. - Flipping a sign in one of the two heaps:
top_heapmust surface the worst insider(count, -value)whilerest_heapsurfaces the best outsider(-count, value). Getting-valuevsvaluebackwards only fails on equal-count ties.
Alternative approaches
- Bucket sort for Mode 1 (
O(n)time): bucket sort groups items into an array of lists indexed by their integer count1..nand walks from bucketndown to1. It avoids thelog kheap factor, though enforcing "smaller value first" requires sorting the final partial bucket if ties exist. - Balanced binary search tree / sorted list (
O(log d)per update): in languages with a built-in ordered set (TreeSetin Java,std::setin C++, or third-partysortedcontainers.SortedListin Python), storing(-count, value)lets each update remove the old pair and insert the new pair inO(log d)without lazy deletion. Python's standard library does not include a balanced tree, which is why the two-heap design is ideal here. - Doubly linked list of frequency buckets (LFU-cache layout): a doubly linked list (a chain of nodes where each node points to both its previous and next neighbor for
O(1)insertion and removal) of count buckets updates+1/-1counts inO(1)time when tie order does not matter, though breaking ties by smallest integer value reintroduces logarithmic ordering inside each bucket.
Follow-up questions
- How would you approximate Top-K frequencies when a stream contains billions of distinct keys that exceed available RAM? Use a heavy-hitter sketch (a compact probabilistic summary that tracks frequent items in fixed memory with a bounded error). For example, the Space-Saving algorithm keeps only
mcounters (saym = 10,000) and evicts the minimum counter on a miss, guaranteeing every item with frequency aboven / mis retained; alternatively, a Count-Min sketch (ad x wgrid of hash counters that estimates any item's count within+epsilon * nwith probability1 - delta) can be paired with a small size-kheap of current leaders. - How can you bound memory usage in the 1-hour sliding window when millions of events arrive every hour? Use time bucketing (aggregating raw events into fixed time slices such as 1-second mini-counters instead of storing every raw event). A deque of
(second, Counter)holds at most3,601per-second buckets no matter how high the event rate spikes, and expiring one bucket simply subtracts each(value, bucket_count)fromTopKCounter— which still needs at most one swap per value adjusted. - If the stream is sharded across 10 worker nodes, can an aggregator simply merge each node's local Top-K list? Not if keys are routed randomly: with
k = 2, if node A has{a: 10, b: 10, c: 9}and node B has{d: 10, e: 10, c: 9}, neither node reportscin its local Top 2 even thoughcleads globally with18. To make merging exact, shard the stream by hashingvalue(hash(value) % num_nodes) so all occurrences of a given integer land on the same worker; then the global Top-K is guaranteed to sit inside the union of each worker's local Top-K.
Follow-up questions
- How would you approximate Top-K frequencies when a stream contains billions of distinct keys that exceed available RAM?
- How can you bound memory usage in the 1-hour sliding window when millions of events arrive every hour?
- If the stream is sharded across 10 worker nodes, can an aggregator simply merge each node's local Top-K list?
Similar questions
- Enum-Driven Restaurant Menu Manager
- In-Memory User File Store with Quota Eviction
- Point-of-Sale Receipt Engine with Promotional Bundles
- Thread-Safe Kitchen Order Queue and Pickup Coordinator
- Menu Tree Parser and Serializer
- Real-Time Kitchen Order Storage and Fulfillment Engine
More CloudKitchens interview questions
- In-Memory User File Store with Quota Eviction Medium
- Enum-Driven Restaurant Menu Manager Medium
- Real-Time Kitchen Order Storage and Fulfillment Engine Medium Pro
- Point-of-Sale Receipt Engine with Promotional Bundles Medium Pro
- Thread-Safe Kitchen Order Queue and Pickup Coordinator Medium Pro
- Menu Tree Parser and Serializer Medium Pro