Frequency Tracking with Static and Streaming Top-K Retrieval
Data Structure DesignModel answerLast updated
Build data structures to identify the most frequent elements in three scenarios: a fixed array, an unbounded stream, and a time-windowed stream.
Problem Statement
Design solutions for tracking and retrieving the most frequent elements across three different scenarios.
Part 1: Fixed Collection
You're given an array nums containing n integers and a positive integer k. Return the k values that appear most frequently in the array.
Input:
nums: array of integersk: number of elements to return
Output: List of k most frequent values
Tie-breaking: When multiple values have the same frequency, prefer smaller values.
Part 2: Continuous Stream
Design a data structure that processes an infinite stream of integers and supports:
insert(value): Record one occurrence of the given valuequery(): Return thekmost frequent values seen so far
The structure should handle repeated calls to both operations efficiently.
Part 3: Time-Windowed Stream
Extend the streaming solution to handle temporal data. Events arrive as (time, value) pairs where timestamps are monotonically non-decreasing (measured in seconds).
Support these operations:
record(timestamp, value): Log an eventgetTopK(timestamp): Return thekmost frequent values within the time range[timestamp - 3600, timestamp](events from the last hour, inclusive)
Requirements
- For all three parts: if fewer than
kdistinct values exist, return all available values - Output should be deterministic and sorted by rank (most frequent first)
- Discuss time and space complexity for each variant
- Consider edge cases: duplicate frequencies, sparse vs. dense data, bursts of identical events
Constraints
Assume up to 200,000 operations unless you choose different bounds.
Hints
Hint 1
For the fixed array, you don't need to fully sort all distinct elements—a partial selection algorithm is more efficient.
Hint 2
In the unbounded stream, counts only go up. Can you maintain the top-k set incrementally without recalculating from scratch each time?
Hint 3
For the sliding window, think about efficient expiration: grouping events by timestamp reduces the overhead of removing old data.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
Part 1: Fixed Collection
Strategy
Build a frequency map, then select the best k elements using a partial selection algorithm rather than full sorting.
Algorithm:
- Count occurrences using a hash map
- Use a min-heap of size
kor theheapq.nsmallestfunction with a custom key - The key is
(-frequency, value)to prioritize high frequency and break ties with smaller values
Why this works: We only need the top k elements, not a complete ordering of all distinct values. Heap selection achieves this in O(d log k) where d is the number of distinct values, versus O(d log d) for full sorting.
Complexity:
- Time:
O(n + d log k)wherenis array length andd ≤ ndistinct values - Space:
O(d)for the frequency map
Alternative: Bucket sort by frequency runs in O(n) time. Create buckets indexed by count, then iterate from highest frequency downward. This linear-time approach is worth mentioning for very large inputs.
import heapq
from collections import Counter
def topKFrequent(nums, k):
if k <= 0:
return []
freq = Counter(nums)
return heapq.nsmallest(k, freq.keys(), key=lambda x: (-freq[x], x))
Part 2: Continuous Stream
Challenge
Recalculating top-k on every query by scanning all distinct values costs O(d log k) per query. We can exploit a key insight: counts are monotonically increasing.
Strategy
Maintain a set candidates holding the current top k values. When insert(x) increments the count:
- If
xis already incandidates, it remains valid (its rank only improved) - If
candidateshas room (< k elements), addx - Otherwise, compare
xagainst the weakest element incandidates. Ifxnow ranks better, evict the weakest and insertx
To efficiently find the weakest element, maintain a min-heap keyed by (count, -value). Use lazy deletion: instead of updating heap entries when counts change, push new entries and skip stale ones when peeking.
Invariant: candidates contains exactly the top min(k, d) values at all times.
Complexity:
insert: AmortizedO(log h)wherehis heap size (each element creates at most one heap entry across its lifetime)query:O(k log k)to sort the candidate set- Space:
O(d + k)if we periodically rebuild the heap;O(d + total_inserts)worst-case without rebuilding
class StreamFrequency:
def __init__(self, k):
self.k = k
self.counts = {}
self.candidates = set()
self.heap = [] # min-heap of (count, -value, value)
def _ranks_better(self, a, b):
ca, cb = self.counts[a], self.counts[b]
return ca > cb or (ca == cb and a < b)
def _get_weakest(self):
while True:
count, _, val = self.heap[0]
if val in self.candidates and self.counts[val] == count:
return val
heapq.heappop(self.heap) # discard stale entry
def insert(self, x):
self.counts[x] = self.counts.get(x, 0) + 1
if x in self.candidates:
heapq.heappush(self.heap, (self.counts[x], -x, x))
elif len(self.candidates) < self.k:
self.candidates.add(x)
heapq.heappush(self.heap, (self.counts[x], -x, x))
else:
weakest = self._get_weakest()
if self._ranks_better(x, weakest):
heapq.heappop(self.heap)
self.candidates.remove(weakest)
self.candidates.add(x)
heapq.heappush(self.heap, (self.counts[x], -x, x))
def query(self):
return sorted(self.candidates, key=lambda x: (-self.counts[x], x))
Part 3: Time-Windowed Stream
New Challenge
Counts now decrease as events expire. The incremental update strategy breaks because an element outside candidates can surpass a member when the member's count drops.
Strategy
-
Bucket events by timestamp: Use a deque where each entry is
(second, frequency_map). This groups events occurring in the same second, avoiding one deque node per event. -
Lazy expiration: When processing
recordorgetTopKat timet, remove all buckets with timestamp <t - 3600. Subtract their counts from the global frequency map and delete zeroed entries. -
Query: Run heap selection over the current live frequencies:
heapq.nsmallest(k, counts, key=lambda x: (-counts[x], x))
Amortized cost: Each event is inserted once and expired once, so expiration is O(1) amortized per event.
Optimization for query-heavy workloads: If getTopK is called frequently relative to the number of distinct values, maintain a sorted structure (like a balanced BST or SortedList) of (-count, value) pairs:
- Each count change: remove old entry and insert new entry in
O(log d) - Query: read first
kentries inO(k)
This trades faster queries for slower updates. Mention this tradeoff to show you understand when different structures are appropriate.
Complexity (heap-based):
record: AmortizedO(1)for insertion and expirationgetTopK:O(d_w log k)whered_wis distinct values in the window- Space:
O(min(events_in_window, 3601 × max_distinct_per_second))
from collections import Counter, deque
class WindowedFrequency:
def __init__(self, k):
self.k = k
self.window_size = 3600
self.buckets = deque() # [(timestamp, Counter)]
self.counts = Counter()
def _expire_old(self, current_time):
cutoff = current_time - self.window_size
while self.buckets and self.buckets[0][0] < cutoff:
_, old_counts = self.buckets.popleft()
for val, count in old_counts.items():
self.counts[val] -= count
if self.counts[val] == 0:
del self.counts[val]
def record(self, timestamp, value):
self._expire_old(timestamp)
if self.buckets and self.buckets[-1][0] == timestamp:
self.buckets[-1][1][value] += 1
else:
self.buckets.append((timestamp, Counter([value])))
self.counts[value] += 1
def getTopK(self, timestamp):
self._expire_old(timestamp)
if not self.counts:
return []
return heapq.nsmallest(self.k, self.counts.keys(),
key=lambda x: (-self.counts[x], x))
Edge Cases and Common Mistakes
- k = 0 or k > distinct values: Return empty list or all available values respectively
- Ties at the boundary: Deterministic tie-breaking (smaller value wins) prevents flaky tests
- All unique values: When
d = n, the algorithms still work correctly without special handling - Window boundary: Events at exactly
t - 3600are included (closed interval) - Long gaps in Part 3: A query after no events for hours correctly returns an empty list after expiring everything
- Common mistake: Forgetting to handle the case where the heap contains stale entries in Part 2
- Common mistake: Creating one deque node per event in Part 3 instead of bucketing by second, leading to memory bloat during bursts