Implement sliding-window device anomaly
Company: PayPal
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: This question evaluates understanding of streaming algorithms, sliding-window state management, per-user data structures, and handling out-of-order events under strict time and space complexity constraints.
Constraints
- Events are given in non-decreasing timestamp order.
- Window length is 600 seconds (10 minutes), inclusive: [ts - 599, ts].
- Only events with success == True count toward the distinct-device total.
- Alert threshold is >= 4 distinct device_ids.
- Emit at most one alert per user per distinct window_end_ts.
- 0 <= len(events); timestamps fit in a 64-bit integer.
Examples
Input: ([],)
Expected Output: []
Explanation: Empty stream produces no alerts.
Input: ([('u1', 0, 'd1', True), ('u1', 100, 'd2', True), ('u1', 200, 'd3', True)],)
Expected Output: []
Explanation: Only 3 distinct devices in the window — below the threshold of 4.
Hints
- Keep one deque of (ts, device_id) per user. Append on each successful event, then pop from the front while the oldest timestamp is older than ts - 599.
- The window must include the current event, so window_start = ts - 600 + 1; the oldest surviving deque entry's ts is window_start_ts in the alert.
- To hit the amortized O(1)-O(log K) target, maintain a device_id -> count map alongside the deque: increment on append, decrement on eviction, and track distinct as the number of keys with count > 0 instead of rebuilding a set each time.
- Failed logins (success == False) are skipped entirely — they neither count nor enter the deque.