Answer static and streaming Top-K queries
CloudKitchensSoftware Engineer · Technical ScreenLast updated
This question evaluates understanding of frequency counting, top-K selection, streaming and sliding-window algorithms and data-structure design in the Coding & Algorithms domain, testing both conceptual algorithmic reasoning and practical implementation skills.
Top-K in static and streaming settings (3 variants)
You are given integers and asked to answer Top-K queries under three different scenarios.
Variant 1: Static Top-K
Given an array A of n integers and an integer k, return the k most frequent values.
- Input:
A(lengthn),k - Output: list of
kvalues (any order is acceptable unless you specify tie-breaking) - Clarify tie-breaking for equal frequencies (e.g., smaller value first, or any order).
Variant 2: Real-time (unbounded) streaming Top-K
You receive a stream of integers supporting operations:
add(x): add one occurrence of valuextopk(): return the currentkmost frequent values
Design an efficient data structure and implement these operations.
Variant 3: Real-time Top-K within the last 1 hour (sliding window)
Events arrive as (timestamp, value) where timestamp is in seconds (monotonic non-decreasing). Support:
add(t, x): record eventxat timettopk(t): return thekmost frequent values considering only events with timestamps in[t-3600, t]
Constraints to assume (unless you choose others)
nup to 2e5 for the static problem.- Streaming operations up to 2e5.
- Values may repeat heavily.
What to discuss
- Time/space complexity tradeoffs for each variant.
- How you maintain counts and retrieve Top-K efficiently, especially for the sliding window case.
- Edge cases: fewer than
kdistinct values, ties, many unique values, bursts of events.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.