Find Frequent Elements in Large-Scale Data Streams
Heaps, Sorting & SearchModel answerLast updated
Design scalable algorithms to extract the top K most frequent elements from a data stream under both memory-bounded exact and memory-constrained approximate regimes.
You are tasked with processing a dynamic stream of incoming elements (such as user IDs, IP addresses, or search terms). The dataset can be very large or potentially continuous. Design a system that can return the $K$ most frequent elements seen so far.
Your solution must address two main operational scenarios:
- Exact Mode (Memory Fits Unique Keys): When the system has sufficient RAM to track every distinct element, output the exact top-$K$ items along with their true counts.
- Approximate Mode (Unique Keys Exceed Memory): When unique elements far exceed available space, maintain a streaming summary using limited memory. Explain the accuracy guarantees, error bounds, and trade-offs.
For both approaches, detail the time complexity for updating an element and querying the top $K$, as well as the overall space complexity. Provide a clean implementation in code covering both modes.
Hints
Hint 1
For the exact approach, consider how to minimize query latency using a min-heap rather than sorting all collected keys.
Hint 2
For bounded memory streaming, research summary algorithms like Space-Saving or Misra-Gries. Think about what error bound is guaranteed when using a fixed counter size $m$.
Hint 3
Pay attention to how eviction works in Space-Saving: replacing the minimum key guarantees that frequent keys above a threshold $N/m$ are never lost.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach Overview
This problem presents a classic trade-off between exact state tracking and bounded-memory streaming estimation. A complete answer requires addressing both memory regimes:
-
Exact Solution (Exact Frequency Map):
- Data Structures: A hash map to map each key to its frequency, and a min-heap of size $K$ to extract the top items during a query.
- Properties: Memory is proportional to $D$, the number of distinct items in the stream ($O(D)$ space), regardless of the total stream size $N$.
-
Approximate Solution (Space-Saving Algorithm):
- Data Structures: A fixed-capacity table of $m$ counters (where $m \ge K$), tracking
(item, count, error). - Mechanism:
- If an incoming element is already tracked, increment its count.
- If space remains, add the new element with
count = 1anderror = 0. - If the table is full, locate the key with the minimum count $c_{\min}$. Replace it with the incoming item, update its count to $c_{\min} + 1$, and record its maximum possible overcount error as $e = c_{\min}$.
- Guarantees: Any item whose true frequency exceeds $N/m$ is guaranteed to be present in the counter table. The estimated frequency $\hat{f}$ satisfies $f \le \hat{f} \le f + N/m$.
- Data Structures: A fixed-capacity table of $m$ counters (where $m \ge K$), tracking
Complexity Analysis
| Metric / Mode | Exact Mode | Space-Saving (Naïve Eviction) | Space-Saving (Stream-Summary DS) |
|---|---|---|---|
| Stream Update Time | $O(1)$ average | $O(m)$ scan for minimum | $O(1)$ using doubly-linked bucket list |
| Top-K Query Time | $O(D \log K)$ | $O(m \log K)$ | $O(m \log K)$ or $O(K)$ |
| Space Complexity | $O(D)$ | $O(m)$ | $O(m)$ |
Note on Error Bound $\varepsilon$: Setting $m = \lceil 1/\varepsilon \rceil$ bounds the absolute count error to at most $\varepsilon N$. For heavily skewed distributions (e.g., Zipfian distributions typical in web traffic), setting $m = 10K \text{ to } 100K$ delivers exact top-$K$ results in practice while using orders of magnitude less memory than full tracking.
Implementation
import heapq
from collections import Counter
from typing import Hashable, List, Tuple
class ExactTopK:
"""Exact stream counter for cases where distinct keys fit in memory."""
def __init__(self) -> None:
self.frequencies: Counter = Counter()
def add(self, item: Hashable) -> None:
"""Process an incoming item from the stream."""
self.frequencies[item] += 1
def top_k(self, k: int) -> List[Tuple[Hashable, int]]:
"""Return top k items as (item, exact_count)."""
if k <= 0:
return []
# Uses a min-heap under the hood: O(D log k)
return heapq.nlargest(k, self.frequencies.items(), key=lambda x: x[1])
class SpaceSavingTopK:
"""Approximate top-k using the Space-Saving summary algorithm.
Guarantees:
- Absolute error per item count is bounded by N / capacity.
- Any item with frequency > N / capacity is guaranteed to be retained.
"""
def __init__(self, capacity: int) -> None:
if capacity <= 0:
raise ValueError("Capacity must be positive")
self.capacity = capacity
self.counts: dict[Hashable, int] = {}
self.errors: dict[Hashable, int] = {}
self.total_stream_count = 0
def add(self, item: Hashable) -> None:
"""Process an incoming item from the stream."""
self.total_stream_count += 1
if item in self.counts:
self.counts[item] += 1
elif len(self.counts) < self.capacity:
self.counts[item] = 1
self.errors[item] = 0
else:
# Evict key with minimum count
min_key = min(self.counts, key=self.counts.__getitem__)
min_val = self.counts.pop(min_key)
del self.errors[min_key]
# Assign evicted key's count + 1 to new item
self.counts[item] = min_val + 1
self.errors[item] = min_val
def top_k(self, k: int) -> List[Tuple[Hashable, int, int]]:
"""Returns top k items as tuples: (item, estimated_count, min_guaranteed_count)."""
if k <= 0:
return []
top_items = heapq.nlargest(k, self.counts.items(), key=lambda x: x[1])
return [(item, est, est - self.errors[item]) for item, est in top_items]
def is_exact_guarantee(self, k: int) -> bool:
"""Checks if the reported top-k set is provably identical to the true top-k set."""
if len(self.counts) < self.capacity:
return True
top_k_plus_1 = heapq.nlargest(k + 1, self.counts.items(), key=lambda x: x[1])
if len(top_k_plus_1) <= k:
return True
kth_item, kth_est = top_k_plus_1[k - 1]
kth_min_bound = kth_est - self.errors[kth_item]
next_max_bound = top_k_plus_1[k][1]
# If lower bound of K-th item exceeds upper bound of (K+1)-th item
return kth_min_bound >= next_max_bound
Edge Cases & Practical Considerations
- Capacity $m < K$: $m$ must be strictly $\ge K$. In production systems, setting $m \gg K$ (e.g., $m = 20K$) yields higher precision.
- Ties in Frequencies: The min-heap uses deterministic ordering based on item values or insertion order. If precise ordering for tied elements is required, append tie-breaker metadata to items.
- Distributed Streaming Datasets:
- Exact Sharding: Partition elements across nodes using consistent hashing
hash(key) % total_shards. Each worker computes local frequencies independently, and a master node collects and aggregates the top $K$ candidates. - Mergeable Summaries: Space-Saving and Count-Min summaries are sketch structures that can be combined across parallel map workers before executing a final top-$K$ reduction.
- Exact Sharding: Partition elements across nodes using consistent hashing