← 返回 snapchat 的题目列表Stream Window Max Unique Users
类型:qbank
Given timestamped user events and a window size, find the maximum number of unique users appearing in any time window.
Requirements
Given a list of events and a window size, compute the maximum number of distinct users in any window.
Input shape:
events = [(timestamp, user_id), ...]
window_size = W
Expected behavior:
Events may need to be sorted by timestamp.
A window contains events whose timestamps fall within a width of W.
Count unique user_id values in the current window.
Return the maximum unique-user count across all windows.
Clarify inclusive vs exclusive window endpoints before coding.
Notes
Sort by timestamp, then use a two-pointer sliding window. Maintain a frequency map from user id to count for events inside the window. When the right pointer advances, increment that user's count; while the window is too wide, decrement the left user's count and remove it when the count reaches zero. The number of keys in the map is the current unique-user count.
If timestamps can repeat, the pointer logic still works as long as the endpoint rule is consistent. If the stream is already sorted and unbounded, the same algorithm can run online with a queue for active events.
Complexity is O(n log n) if sorting is needed, or O(n) for pre-sorted input. Space is O(k) for users in the current window.
Preparation
Write the sorted-array version and the online-stream version.
Test duplicate user events inside one window, identical timestamps, empty input, and window size zero if allowed.
Practice explaining endpoint semantics with an example before implementing.