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 [].

  1. Mode 1 — Batch array (top_k_frequent):
    • top_k_frequent(nums: List[int], k: int) -> List[int] returns the top k integers from nums.
  2. Mode 2 — Unbounded stream (StreamingTopK):
    • StreamingTopK(k: int) initializes an empty stream tracker (k >= 0; raise ValueError if k < 0).
    • add(x: int) -> None records one arrival of integer x.
    • topk() -> List[int] returns the current top k integers over all arrivals seen so far.
  3. Mode 3 — Sliding time window (SlidingWindowTopK):
    • SlidingWindowTopK(k: int, window: int = 3600) tracks arrivals within a trailing window-second span (k >= 0 and window >= 0; raise ValueError if either is negative).
    • add(t: int, x: int) -> None records integer x at integer second t.
    • topk(t: int) -> List[int] returns the top k integers counting only arrivals whose timestamps lie in the closed interval [t - window, t] (both endpoints included).
    • Timestamps passed to add and topk never move backward; if a call supplies t strictly less than the preceding call's timestamp, raise ValueError.

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^5 in top_k_frequent.
  • Up to 2 * 10^5 total add and topk calls on StreamingTopK or SlidingWindowTopK.
  • Input integers can be negative, zero, or positive, and duplicates may be frequent or bursty at identical timestamps.
  • StreamingTopK and SlidingWindowTopK require k >= 0 (and window >= 0), raising ValueError otherwise; SlidingWindowTopK raises ValueError whenever timestamp t decreases relative to the prior call.

Step-by-step walkthrough

  1. Understand the three variants and the tie-break rule

    All three variants ask for the k most 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 k distinct values have positive counts, return all of them (best first). If k <= 0, return [].
    • Inclusive window: in Variant 3, a query at timestamp t includes every event whose timestamp s satisfies t - 3600 <= s <= t (both endpoints included). Because timestamps are monotonic non-decreasing across calls, passing a timestamp smaller than the previous call raises ValueError.

    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]: ...
    
  2. Variant 1: count frequencies and keep K with a heap

    For a static array nums of length n, we first count how often each distinct integer appears using a hash map (Counter(nums)), which takes one O(n) pass. Suppose d distinct values appear (d <= n).

    To select the best k out of those d distinct values without sorting all d items when k is small, we pair each value with the rank tuple (-count, value):

    • Python compares tuples left-to-right.
    • Negating count makes a higher frequency look smaller (-3 < -2), while leaving value positive makes a smaller integer win ties ((-2, 2) < (-2, 4)).
    • heapq.nsmallest(k, ranked_candidates) maintains a heap of only k items in O(d log k) time and returns those k tuples sorted best-first.

    Trace Example 1 on nums = [8, 3, 8, 5, 3, 8, 5, 2] with k = 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 result
    
  3. Why Variants 2 and 3 cannot re-sort on every query

    A tempting shortcut for streaming is to update counts[x] += 1 in O(1) inside add(x) and run Variant 1's heapq.nsmallest inside topk(). That works if queries are rare, but fails when queries are frequent:

    • Suppose 200,000 operations alternate between add(new_value) and topk().
    • The i-th query scans i distinct entries in counts.
    • Across 100,000 queries, total work is 1 + 2 + ... + 100,000 ≈ 5 * 10^9 operations — 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-k winners can change by at most one item:

    1. If fewer than k live items are in the top set (or a top item's count just fell to 0), the single best outsider steps into the empty spot.
    2. 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.

  4. Split live values across two heaps with lazy deletion

    We build one reusable TopKCounter that supports both increment(value) and decrement(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 (heapq always puts the smallest tuple at index 0):

    • rest_heap stores (-count, value): higher count gives a more negative first number, and smaller value wins ties, so rest_heap[0] is the best outsider.
    • top_heap stores (count, -value): exact opposite signs! Lower count comes first, and larger value (-value is more negative) comes first on ties, so top_heap[0] is the worst member of in_top.

    Python's heapq cannot 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 inspect top_heap[0] or rest_heap[0], we verify that the value still belongs to that side and its stored count still equals self.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))
    
  5. Update counts, rebalance the boundary, and compact stale entries

    Now we write _change(value, delta) and _rebalance():

    1. Update counts: if new_count == 0, delete value from counts and in_top (any old tuples in the heaps are now automatically recognized as stale). Otherwise store new_count and push a fresh tuple onto top_heap (if value in self.in_top) or rest_heap.
    2. Rebalance: first fill in_top up to size k from rest_heap if room exists, then check whether best_rest strictly beats worst_top by comparing their rank tuples (-count, value). If so, pop both roots and swap their groups.
    3. Prevent stale buildup (_compact): in a long sliding-window run, stale entries deep inside a heap might sit unpopped while d (the number of live distinct values) stays small. Whenever len(top_heap) + len(rest_heap) > 2 * d + 16, we rebuild both heaps from self.counts using heapq.heapify in O(d) time. Because > 2d + 16 entries shrink down to d live entries, every rebuild destroys more than d + 16 stale entries that were each pushed once — so rebuilds add only O(1) amortized work per heap push.

    Finally, topk() only sorts the <= k items inside self.in_top, taking O(k log k) time regardless of how large d grows.

        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)
    
  6. Wrap the counter for unbounded streams and sliding windows

    With TopKCounter ready, Variants 2 and 3 become small, clean wrappers:

    • StreamingTopK (Variant 2): delegates add(x) to counter.increment(x) and topk() to counter.topk().
    • SlidingWindowTopK (Variant 3): keeps a collections.deque of (timestamp, value) pairs in arrival order. Because timestamps never decrease, the oldest un-expired event is always at events[0]. Both add(t, x) and topk(t) call _advance(t) first to pop events strictly older than t - window (timestamp < t - window, keeping t - window itself inside the window) and decrement their counts.

    Trace Example 3 on SlidingWindowTopK(k=1, window=3600) when 20 arrives three times at t = 10 and 30 arrives twice at t = 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) needs rest_heap: as 20 decrements 3 -> 2 -> 1 -> 0, 30 was waiting outside in_top and 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()
    
  7. 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):

  1. add(6) -> counts {6: 1}, VIP in_top = {6}, rest = {}, topk() is [6].
  2. add(4) -> counts {6: 1, 4: 1}, VIP has room so in_top = {4, 6}, topk() is [4, 6] (4 beats 6 on the tie).
  3. add(4) -> counts {4: 2, 6: 1}, in_top = {4, 6}, topk() is [4, 6].
  4. First add(9) -> counts {4: 2, 6: 1, 9: 1}; 9 enters rest, and its rank (-1, 9) does not beat weakest VIP 6 with rank (-1, 6), so in_top stays {4, 6}.
  5. Second add(9) -> counts {4: 2, 9: 2, 6: 1}; challenger 9 now has rank (-2, 9), beating weakest VIP 6 ((-1, 6)), so 9 and 6 swap -> in_top = {4, 9}, rest = {6}.
  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 all n integers once to build the frequency map (O(n)), then pass the d (count, value) pairs through heapq.nsmallest(k, ...), which maintains a heap of size at most k (O(d log k), or O(d log d) when k >= d).
  • Mode 1 space — O(d): the Counter dictionary 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 +1 or -1 change 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 exceed 2d + 16, _compact rebuilds both heaps in O(d) time; because shrinking > 2d + 16 entries down to d live entries destroys more than d + 16 stale entries that were each pushed once, rebuilds add only O(1) amortized work per push. In Mode 3, each event enters the deque once on add and leaves once on expiry, so both add and expiry cost O(log d) amortized per event.
  • Modes 2 & 3 query time (topk) — O(k log k) (plus expiring old events in Mode 3): topk only sorts the <= k integers currently stored in in_top, completely independent of d.
  • Modes 2 & 3 space — O(d) for Mode 2, O(d + W) for Mode 3: compaction caps both heaps at roughly 2d + 16 entries alongside the O(d) dictionary and set, while Mode 3 also stores the W active (timestamp, value) events in its deque.

Edge cases

  • Fewer than k distinct values or k <= 0: when fewer than k distinct values exist, in_top holds all of them (top_k_frequent([12, 12, 19], 5) returns [12, 19]). When k <= 0, top_k_frequent returns [] (and k == 0 on the classes returns []).
  • Exact frequency ties: ties are broken consistently by smaller integer value in top_heap (using -value), in rest_heap (using +value), and in topk(). With k = 1, calling add(8) then add(2) immediately flips topk() from [8] to [2].
  • Negative numbers and zero: negating value inside top_heap reverses order cleanly for negative, zero, and positive integers alike (-(-7) = 7 > -(-4) = 4, so -7 beats -4 on ties).
  • Many distinct values with frequent queries: topk() sorts at most k items rather than scanning d items, staying fast even when 30,000 distinct values are queried after every add.
  • Inclusive window boundary [t - 3600, t]: in Example 3, an event at timestamp 10 is still valid at t = 3610 (10 < 3610 - 3600 is False) and expires at t = 3611 (10 < 11 is True).
  • Queries after a long silence: calling topk(t) runs _advance(t) before reading in_top, so querying more than an hour after the last add properly returns [].
  • Out-of-order timestamps: if t < last_time on either add or topk, _advance raises ValueError rather than corrupting the chronological order of the deque.

Common mistakes

  • Using Counter.most_common(k) without handling ties: most_common breaks 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 counts inside topk(): scanning all d distinct keys on every query turns Q queries into O(Q * d log k) work, which times out when queries are frequent.
  • Keeping only a single min-heap of size k in 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 in heapq. You must push a fresh tuple and verify counts when reading heap roots.
  • Using <= instead of < when expiring events: popping while timestamp <= t - window wrongly drops events at exact timestamp t - 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_heap must surface the worst insider (count, -value) while rest_heap surfaces the best outsider (-count, value). Getting -value vs value backwards 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 count 1..n and walks from bucket n down to 1. It avoids the log k heap 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 (TreeSet in Java, std::set in C++, or third-party sortedcontainers.SortedList in Python), storing (-count, value) lets each update remove the old pair and insert the new pair in O(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 / -1 counts in O(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 m counters (say m = 10,000) and evicts the minimum counter on a miss, guaranteeing every item with frequency above n / m is retained; alternatively, a Count-Min sketch (a d x w grid of hash counters that estimates any item's count within +epsilon * n with probability 1 - delta) can be paired with a small size-k heap 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 most 3,601 per-second buckets no matter how high the event rate spikes, and expiring one bucket simply subtracts each (value, bucket_count) from TopKCounter — 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 reports c in its local Top 2 even though c leads globally with 18. To make merging exact, shard the stream by hashing value (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

Similar questions

More CloudKitchens interview questions

All 7 CloudKitchens questions →