Sliding window unique visitor count
Python data engineering interview problem. Difficulty: advanced. Pattern: Sliding Window. About 20 minutes. Part of the Pro drill bank.
An analytics job counts distinct visitors inside each sliding window of events so a spike of one user does not look like a crowd.
A product team counts how many different visitors were seen in the last few minutes, each time a new event arrives. events is a list of (time, visitor_id) pairs in time order. For each event, count the distinct visitors among events whose time is greater than time - window (the event itself and recent ones). Return a list with one count for each event. An empty list returns []. Write distinct_in_windows(events, window). For [(1, 'a'), (2, 'b'), (8, 'a')] and window 5: at time 1 only a (1 visitor), at time 2 a and b (2), at time 8 events at times 1 and 2 are too old, so only a (1). The result is [1, 2, 1]. The starter file already has the function name and its print lines. Keep them and fill in the body.
Requirements
- Treat the window as the last window time units, not including the boundary.
- Count each visitor once in a window.
- Return one number for each event, in order.
- An empty list returns [].
Constraints
- Events are sorted by time.
- An event is too old when event_time <= current_time - window.
Examples
Input: distinct_in_windows([(1, 'a'), (2, 'b'), (8, 'a')], 5) Output: [1, 2, 1] This input follows the stated rules and produces this output.
Topics: lakebench, python, sliding-window.
More Python interview questions · All interview problems · Learn data engineering
Sliding window unique visitor count
Interview-style drill: For a stream of timestamped visitor ids, report the count of distinct visitors in every trailing 60-second window.
Return the distinct-visitor count for each window of a given size.