This one took me a second to get my footing.
Start by clarifying constraints (K, memory, stream rate, exact vs approximate). Present a two-case solution: exact counting with a hash map when distinct items fit in memory, and an approximate heavy-hitters algorithm (e.g., Misra-Gries or Count-Min Sketch) when they don't. For each, analyze time and space complexity, and discuss trade-offs.
Pro tip: Mention that for the approximate case, you can use a two-pass approach: first identify candidate heavy hitters, then in a second pass count them exactly if a second pass is allowed. This shows you consider practical constraints beyond the basic algorithm.
Ask about K, memory limits, whether exact counts are needed, if multiple passes are allowed, and the stream's characteristics (e.g., skew). This ensures the solution fits the problem context.
Use a hash map to count frequencies of all items, then maintain a min-heap of size K to track top K. Analyze time O(N log K) and space O(D + K) where D is distinct items.
Use a heavy-hitters algorithm like Misra-Gries or Count-Min Sketch to identify candidate frequent items with bounded memory. Explain the trade-off between accuracy and space.
Compare time and space for both approaches. For Misra-Gries, time O(N) and space O(K); for Count-Min Sketch, time O(N) and space O(1/ε log 1/δ). Discuss error guarantees and when to choose each.
Conclude with a recommendation based on constraints, and mention possible optimizations like parallelization or using a second pass for exact counts on candidates.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.