KatInterview

Find Frequent Elements in Large-Scale Data Streams

Heaps, Sorting & SearchModel answer
MediumModel answerHeaps, Sorting & Searchheaps-sortingdesign-dsarrays

Last 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:

  1. 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.
  2. 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.