Multi-Device Transfer Detection in a Sliding Window
Medium · Coding & Algorithms · Data Scientist · Onsite
Problem Statement
Given a batch of payment transfer records across many accounts, identify every user who initiates at least k qualifying transfers from k distinct devices within an inclusive t-minute rolling window, and report the earliest such window per qualifying user.
Implement:
def detect_k_events(events: List[List[object]], k: int, t: int, X: int) -> List[Dict[str, object]]:
Each element of events is a 4-item record [user_id, device_id, ts, amount_cents]:
user_id(int): account identifier.device_id(str): identifier of the client device used for the transfer.ts(str): ISO-8601 timestamp (carrying either"Z"or an explicit UTC offset such as"-05:00").amount_cents(int): transfer value in cents.
Apply the following rules:
- Minimum transfer filter: Only records with
amount_cents >= Xqualify; any record withamount_cents < Xis ignored. - Deduplication: Exact duplicate records—having the same
user_id,device_id, UTC instant, andamount_cents—must be treated as a single event. - Out-of-order arrivals & timezones: Records may arrive up to
5minutes out of chronological order and may use different UTC offsets (including across daylight-saving shifts). Normalize timestamps to UTC instants when ordering and measuring elapsed time. - Inclusive
t-minute span: A group of events fits inside one window whenend_utc - start_utc <= tminutes. - Earliest qualifying window & output format: Return one dictionary per qualifying user (ordered by
user_idascending) containing:"user_id": the integeruser_id,"start_ts": the originaltsstring of the earliest event in that user's earliest qualifying window,"end_ts": the originaltsstring of the event that first brings the window tokdistinct devices, and"device_ids": thekdistinctdevice_idstrings in that window, ordered by their first appearance inside the window.
Users who never reach k distinct devices within t minutes are omitted; return [] when no user qualifies.
Examples
Example 1
Input:
events = [
[410, "ios-1", "2025-02-14T08:10:00Z", 2500],
[410, "web-2", "2025-02-14T08:15:00Z", 3200],
[410, "ipad-3", "2025-02-14T08:22:00Z", 2500],
[520, "mac-1", "2025-02-14T08:12:00Z", 8000]
]
k = 3, t = 15, X = 2500
Output:
[{"user_id": 410, "start_ts": "2025-02-14T08:10:00Z", "end_ts": "2025-02-14T08:22:00Z", "device_ids": ["ios-1", "web-2", "ipad-3"]}]
Account 410 makes three transfers of at least 2500 cents from three different devices across a 12-minute span (08:10 to 08:22, within t = 15). Account 520 only transacts from one device and is omitted.
Example 2
Input:
events = [
[19, "dev-z", "2025-05-20T14:06:00Z", 400],
[19, "dev-x", "2025-05-20T14:01:00Z", 450],
[19, "dev-y", "2025-05-20T14:03:00Z", 400],
[19, "dev-x", "2025-05-20T14:01:00Z", 450]
]
k = 3, t = 6, X = 400
Output:
[{"user_id": 19, "start_ts": "2025-05-20T14:01:00Z", "end_ts": "2025-05-20T14:06:00Z", "device_ids": ["dev-x", "dev-y", "dev-z"]}]
After discarding the duplicate "dev-x" record at 14:01:00Z and sorting by UTC timestamp, "dev-x", "dev-y", and "dev-z" span 5 minutes (<= 6).
Example 3
Input:
events = [
[88, "d1", "2025-08-03T09:00:00Z", 1000],
[88, "d1", "2025-08-03T09:02:00Z", 1200],
[88, "d2", "2025-08-03T09:04:00Z", 999],
[88, "d3", "2025-08-03T09:05:00Z", 1500]
]
k = 3, t = 10, X = 1000
Output:
[]
Device "d2" is filtered out because 999 < 1000, and "d1" firing twice counts as only one device, leaving just two distinct devices ("d1" and "d3").
Constraints
0 <= len(events) <= 10^6k in {3, 4, 5}0 <= t <= 1440X >= 0- Arrival timestamps may be out of order by up to
5minutes. - Target
O(n log n)total time complexity andO(m)active window state, wheremis the maximum number of events for a single user withintminutes.
Step-by-step walkthrough
Restate the problem and pin down the rules
Each input record is
[user_id, device_id, ts, amount_cents]. For every user, we want to find whether there are at leastkqualifying events (amount_cents >= X) fromkdifferent devices whose timestamps all fit withintminutes of each other.Let's pin down the exact rules confirmed by the statement and samples:
- Amount filter (
amount_cents >= X): transfers strictly belowXare ignored completely (in Example 3,999 < 1000does not count). Transfers equal toXcount. - Deduplication: exact duplicate events (same
user_id,device_id, UTC instant, andamount_cents) are ignored. - Inclusive
t-minute span: a window[start_ts, end_ts]is valid whenend_moment - start_moment <= tminutes. - Earliest window: for each qualifying user, return one dictionary
{"user_id", "start_ts", "end_ts", "device_ids"}for the earliest valid window, keeping original timestamp strings (start_ts,end_ts) and omitting users who never reachkdistinct devices. - UTC comparison: events can arrive up to
5minutes out of order and carryZor timezone offsets like-05:00, so we convert timestamps to UTC instants and sort per user before scanning.
- Amount filter (
Why a fixed-start scan is too slow
After sorting one user's qualifying events by time, a straightforward brute-force check picks each index
leftas the window start and walksrightforward until eitherkdistinct devices appear orrightis more thantminutes pastleft.Why does that miss the
O(n log n)requirement? Suppose one active user hasmevents packed insidetminutes from onlyk - 1devices. Starting fromleft = 0scansmevents, starting fromleft = 1scansm - 1events, and so on —O(n * m)work overall, which approaches10^12steps whenn = 10^6.Key idea: two-pointer sliding window with per-device counts
Notice that as
rightmoves forward to a newer timestamp, the cutoffmoment_right - t minutesalso moves forward — so any old event that fell out of the window forrightcan never fit in the window forright + 1!That means both
leftandrightonly ever move forward. Insideuser_events[left..right], we trackcounts[device_id]— how many events inside the current window belong to each device, deleting a key whenever its count drops to0solen(counts)is always the number of distinct devices inO(1)time.Why do we need a count per device instead of a plain
set? Look atk = 3, t = 10ona@0, b@3, a@9, c@12:minute: 0 3 9 12 events: a@0 b@3 a@9 c@12 |<----- 9 min <= 10 ----->| valid window [3, 12] with devices b, a, c! At right=2 (a@9): window [0..2] has counts = {'a': 2, 'b': 1} At right=3 (c@12): 12 - 0 = 12 > 10 -> evict a@0! - With a plain set: removing 'a' leaves {'b', 'c'} (only 2 devices — misses [3, 12]!) - With counts dict: counts['a'] drops 2 -> 1, so counts = {'a': 1, 'b': 1, 'c': 1} (3 devices!)Even better, stopping at the very first
rightwherelen(counts) >= kguarantees:- Earliest
end_ts: no validk-device set ended earlier, or a smallerrightwould already have hadlen(counts) >= k. - Earliest
start_ts: every event beforeleftis more thantminutes beforeright, so anyk-device set starting beforeleftwould have had to end strictly beforeright(impossible by point 1). - Exact
kdevices: one step earlierlen(counts)was at mostk - 1, and addinguser_events[right]adds at most1new device, solen(counts)is exactk.
- Earliest
Parse ISO-8601 timestamps into UTC and group by user
ISO-8601 strings (such as
"2024-03-10T01:59:00-05:00"and"2024-03-10T06:58:00Z") cannot be compared as raw text when offsets differ:As raw strings: "2024-03-10T01:59:00-05:00" < "2024-03-10T06:58:00Z" (wrong!) Converted to UTC: 2024-03-10 06:59:00 UTC > 2024-03-10 06:58:00 UTC (01:59 EST is 1 min LATER)Converting every timestamp to a timezone-aware UTC
datetimegives continuous elapsed time immune to daylight-saving transitions. While grouping byuser_id, we immediately skipamount < Xand drop exact duplicates via aseenset, keeping the originaltsstring so we can echo it in the output.from datetime import datetime, timedelta, timezone def parse_timestamp(ts: str) -> datetime: # Convert an ISO-8601 string (e.g. "2025-02-14T08:10:00Z" or "...-05:00") to an aware UTC datetime. text = ts.strip() if text.endswith("Z") or text.endswith("z"): # Replace trailing 'Z' with '+00:00' so datetime.fromisoformat works on all Python 3 versions. text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) # Normalizing every instant to UTC prevents daylight-saving jumps and mixed-offset comparison bugs. return moment.astimezone(timezone.utc) def group_qualifying_events( events: List[List[object]], X: int ) -> Dict[Any, List[Tuple[datetime, str, str]]]: # by_user: maps user_id -> list of (utc_moment, device_id, raw_ts) for qualifying unique events. by_user: Dict[Any, List[Tuple[datetime, str, str]]] = {} # seen: set of (user_id, device_id, utc_moment, amount) keys used to drop exact duplicates. seen: Set[Tuple[Any, str, datetime, Any]] = set() for user_id, device_id, ts, amount in events: # Filter out transfers below X cents immediately so they never count toward k devices. if amount < X: continue moment = parse_timestamp(ts) dedup_key = (user_id, device_id, moment, amount) if dedup_key in seen: continue seen.add(dedup_key) if user_id not in by_user: by_user[user_id] = [] by_user[user_id].append((moment, device_id, ts)) return by_userWrite the sliding-window sweep
In
find_earliest_window, each event enters the window once whenrightvisits it and leaves at most once whenleftadvances past it:- Notice
while moment - user_events[left][0] > max_span:uses strict>: if two events are exacttminutes apart,>isFalse, keeping both inside the closed[start_ts, end_ts]window. Also, whenleft == right, the difference is0 <= max_span, soleftnever runs pastrighteven whent = 0.
def find_earliest_window( user_events: List[Tuple[datetime, str, str]], k: int, t: int ) -> Optional[Tuple[int, int]]: max_span = timedelta(minutes=t) # counts: maps device_id -> number of its events inside user_events[left..right], e.g. {"a": 2, "b": 1}. # Deleting keys at count 0 makes len(counts) equal the exact number of distinct devices in O(1) time. counts: Dict[str, int] = {} left = 0 for right in range(len(user_events)): moment, device_id, _ = user_events[right] counts[device_id] = counts.get(device_id, 0) + 1 # Strict `>` keeps events that are exactly t minutes apart inside the closed window [start_ts, end_ts]. while moment - user_events[left][0] > max_span: old_device = user_events[left][1] counts[old_device] -= 1 if counts[old_device] == 0: del counts[old_device] left += 1 # Stopping at the very first `right` with >= k distinct devices yields both the earliest end_ts and start_ts. if len(counts) >= k: return left, right return None- Notice
Sort per user and assemble the output
For each
user_idin sorted order,user_events.sort()orders(moment, device_id, ts)chronologically (breaking same-second ties deterministically bydevice_id), repairing any<= 5-minute out-of-order arrivals. Once(left, right)is found,devices_in_ordercollects thekdistinctdevice_ids in order of first appearance using aseen_devicesset forO(1)membership checks.def devices_in_order( user_events: List[Tuple[datetime, str, str]], left: int, right: int ) -> List[str]: # Collect the distinct device_ids inside user_events[left..right] in order of first appearance. devices: List[str] = [] seen_devices: Set[str] = set() for i in range(left, right + 1): device_id = user_events[i][1] if device_id not in seen_devices: seen_devices.add(device_id) devices.append(device_id) return devices def detect_k_events( events: List[List[object]], k: int, t: int, X: int ) -> List[Dict[str, object]]: # Phase 1: Filter to amount >= X, deduplicate exact copies, and bucket by user_id. by_user = group_qualifying_events(events, X) results: List[Dict[str, object]] = [] # Phase 2: Sort each user's events chronologically (repairing out-of-order arrivals) and sweep once. for user_id in sorted(by_user): user_events = by_user[user_id] user_events.sort() window = find_earliest_window(user_events, k, t) if window is None: continue left, right = window results.append({ "user_id": user_id, "start_ts": user_events[left][2], "end_ts": user_events[right][2], "device_ids": devices_in_order(user_events, left, right), }) return resultsWalk through Examples 2 and 3
Example 2: k = 3, t = 6, X = 400 Raw input arrives out of order with a duplicate: dev-z@14:06 (400), dev-x@14:01 (450), dev-y@14:03 (400), dev-x@14:01 (450) After deduplication + user_events.sort(): [dev-x@14:01, dev-y@14:03, dev-z@14:06] right=0 (dev-x@14:01): left=0, span=0m <= 6m, counts={'dev-x': 1} -> 1 device right=1 (dev-y@14:03): left=0, span=2m <= 6m, counts={'dev-x': 1, 'dev-y': 1} -> 2 devices right=2 (dev-z@14:06): left=0, span=5m <= 6m, counts={'dev-x': 1, 'dev-y': 1, 'dev-z': 1} -> 3 devices! Result: [{'user_id': 19, 'start_ts': '...14:01:00Z', 'end_ts': '...14:06:00Z', 'device_ids': ['dev-x', 'dev-y', 'dev-z']}] Example 3: k = 3, t = 10, X = 1000 Raw input: d1@09:00 (1000), d1@09:02 (1200), d2@09:04 (999), d3@09:05 (1500) Filter amount >= 1000 drops d2@09:04 -> [d1@09:00, d1@09:02, d3@09:05] Sweep ends with counts = {'d1': 2, 'd3': 1} -> len(counts) = 2 < 3 -> Result: []Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from datetime import datetime, timedelta, timezone def parse_timestamp(ts: str) -> datetime: # Convert an ISO-8601 string (e.g. "2025-02-14T08:10:00Z" or "...-05:00") to an aware UTC datetime. text = ts.strip() if text.endswith("Z") or text.endswith("z"): # Replace trailing 'Z' with '+00:00' so datetime.fromisoformat works on all Python 3 versions. text = text[:-1] + "+00:00" moment = datetime.fromisoformat(text) if moment.tzinfo is None: moment = moment.replace(tzinfo=timezone.utc) # Normalizing every instant to UTC prevents daylight-saving jumps and mixed-offset comparison bugs. return moment.astimezone(timezone.utc) def group_qualifying_events( events: List[List[object]], X: int ) -> Dict[Any, List[Tuple[datetime, str, str]]]: # by_user: maps user_id -> list of (utc_moment, device_id, raw_ts) for qualifying unique events. by_user: Dict[Any, List[Tuple[datetime, str, str]]] = {} # seen: set of (user_id, device_id, utc_moment, amount) keys used to drop exact duplicates. seen: Set[Tuple[Any, str, datetime, Any]] = set() for user_id, device_id, ts, amount in events: # Filter out transfers below X cents immediately so they never count toward k devices. if amount < X: continue moment = parse_timestamp(ts) dedup_key = (user_id, device_id, moment, amount) if dedup_key in seen: continue seen.add(dedup_key) if user_id not in by_user: by_user[user_id] = [] by_user[user_id].append((moment, device_id, ts)) return by_user def find_earliest_window( user_events: List[Tuple[datetime, str, str]], k: int, t: int ) -> Optional[Tuple[int, int]]: max_span = timedelta(minutes=t) # counts: maps device_id -> number of its events inside user_events[left..right], e.g. {"a": 2, "b": 1}. # Deleting keys at count 0 makes len(counts) equal the exact number of distinct devices in O(1) time. counts: Dict[str, int] = {} left = 0 for right in range(len(user_events)): moment, device_id, _ = user_events[right] counts[device_id] = counts.get(device_id, 0) + 1 # Strict `>` keeps events that are exactly t minutes apart inside the closed window [start_ts, end_ts]. while moment - user_events[left][0] > max_span: old_device = user_events[left][1] counts[old_device] -= 1 if counts[old_device] == 0: del counts[old_device] left += 1 # Stopping at the very first `right` with >= k distinct devices yields both the earliest end_ts and start_ts. if len(counts) >= k: return left, right return None def devices_in_order( user_events: List[Tuple[datetime, str, str]], left: int, right: int ) -> List[str]: # Collect the distinct device_ids inside user_events[left..right] in order of first appearance. devices: List[str] = [] seen_devices: Set[str] = set() for i in range(left, right + 1): device_id = user_events[i][1] if device_id not in seen_devices: seen_devices.add(device_id) devices.append(device_id) return devices def detect_k_events( events: List[List[object]], k: int, t: int, X: int ) -> List[Dict[str, object]]: # Phase 1: Filter to amount >= X, deduplicate exact copies, and bucket by user_id. by_user = group_qualifying_events(events, X) results: List[Dict[str, object]] = [] # Phase 2: Sort each user's events chronologically (repairing out-of-order arrivals) and sweep once. for user_id in sorted(by_user): user_events = by_user[user_id] user_events.sort() window = find_earliest_window(user_events, k, t) if window is None: continue left, right = window results.append({ "user_id": user_id, "start_ts": user_events[left][2], "end_ts": user_events[right][2], "device_ids": devices_in_order(user_events, left, right), }) return results✅ Submit now — all tests should pass.
Intuition & how it works
Imagine inspecting a user's timeline through a movable t-minute viewing frame — a sliding window, meaning a contiguous range [left..right] of time-sorted events whose left and right edges only ever move forward — while keeping a tally sheet (counts) of how many qualifying events inside the frame came from each device. Whenever right steps onto a new event, we add 1 to that device's tally; whenever an event at left is more than t minutes older than right, we advance left and subtract 1 from its tally, erasing the device from counts only when its tally hits 0.
Why do simpler ideas break or run too slow? Re-scanning forward t minutes from every starting event takes O(n * m) time (~10^12 steps when a bursty user sends 10^6 events inside one window), and slicing time into fixed 10-minute clock buckets (like 12:00–12:10 and 12:10–12:20) misses valid bursts that cross a boundary (like 12:08, 12:09, 12:11). Keeping a plain set of devices instead of a per-device count also fails whenever one device fires twice and only its older event expires.
Trace k = 3, t = 10 on sorted qualifying events a@0, b@3, a@9, c@12:
- At
a@0,b@3,a@9, the window holds{a: 2, b: 1}(2distinct devices). - When
c@12arrives,a@0is12 > 10minutes old, soleftmoves tob@3andcounts['a']drops from2to1(deviceastays counted thanks toa@9!). - Now
countsis{a: 1, b: 1, c: 1}(3distinct devices), so we stop immediately and report[3, 12]with devices['b', 'a', 'c'].
Complexity
- Time:
O(n log n), wherenis the total number of input events. Parsing timestamps, filteringamount >= X, and deduplicating withseendoO(1)expected hash-table work per event (O(n)total); sorting each useru'sn_uevents takesO(n_u log n_u), which sums across all users to at mostO(n log n); and infind_earliest_windowbothleftandrightonly advance, so every event enters and leavescountsat most once inO(n_u)time. - Space:
O(n)in batch mode (O(m)for the active window itself), wheremis the maximum events of one user within at-minute horizon. Because the judge passes an arbitrary unpartitioned listevents, grouping and deduplicating across all users stores up tonqualifying events, whereascountsinside the sweep holds at mostmactive devices (and streaming per user bounds total memory per user toO(m), as detailed in the first follow-up).
Edge cases
- Empty input or all amounts below
X:by_userhas no qualifying windows and returns[]; amounts equal toXqualify. - Repeated events from one device (
Example 3):d1@09:00andd1@09:02incrementcounts['d1']to2, contributing only1distinct device towardk. - Exact duplicate events: dropped by
seenusing(user_id, device_id, utc_moment, amount). - Inclusive window boundary (
end - start == tminutes) andt = 0: strict>inmoment - user_events[left][0] > max_spankeeps events exacttminutes apart, and whent = 0it requireskdistinct devices at the exact same timestamp without ever pushingleftpastright. - Mixed timezone offsets and daylight saving time: ISO-8601 (the standard timestamp format like
"2024-03-10T01:59:00-05:00") can carry local offsets around daylight saving time (DST) — seasonal 1-hour wall-clock shifts — so converting every string to UTC (Coordinated Universal Time, a continuous global clock without seasonal jumps) guarantees accurate elapsed minutes.
Common mistakes
- Counting total events instead of distinct
device_ids:3transfers from the same phone are1device, not3. - Using a
setinstead of a reference-counted dictionary: deletingold_devicefrom a set whenuser_events[left]expires wrongly drops a device that still has a newer event inside(left, right]. - Comparing timestamp strings lexicographically:
"2024-03-10T01:59:00-05:00"sorts alphabetically before"2024-03-10T06:58:00Z"even though01:59-05:00is06:59Z(one minute later). - Filtering
amount >= Xtoo late: letting< Xevents enter the window inflateslen(counts)(in Example 3,d2's999-cent transfer would falsely complete3devices). - Continuing to scan for a narrower window: the specification asks for the earliest qualifying window, not the shortest duration, so we must return at the first
rightreachingkdevices.
Alternative approaches
- Per-start forward scan (
O(n * m)time): for eachleft, scanrightforward up totminutes collecting distinct devices. Simple to verify on tiny test cases, but quadratic whenmis large. - Minute-bucket ring buffer: when timestamps are rounded to whole minutes, maintain
t + 1per-minute device sets in a circular array. However, sub-minute timestamps (seconds or milliseconds) break minute buckets around window boundaries unless exact timestamps are kept.
Follow-up questions
- How would you process an unbounded event stream with capped memory when records are partitioned by user ID? Maintain a per-partition watermark — the newest UTC timestamp observed in that partition minus the
5-minute maximum out-of-order skew, guaranteeing no future arrival has a timestamp earlier than the watermark. For each undecided user, buffer incomingamount >= Xevents in a min-heap (a priority queue ordered by earliest timestamp first) plus a small deduplication set for those<= 5minutes of buffered items; whenever buffered events fall strictly at or before the watermark, pop them in sorted order into a deque (a double-ended queue supportingO(1)appends on the right and pops from the left) with the exact samecountsdictionary. Once a user triggerslen(counts) >= k, mark them reported and discard their buffers, bounding each active user's memory toO(m)events over at mostt + 5minutes. - Why is advancing the left pointer monotonically guaranteed to find the earliest valid window without undercounting active devices? Maintain the loop invariant after each
rightstep:user_events[left..right]holds all events in0..rightwithintminutes ofuser_events[right], andcountsmaps each activedevice_idto its exact positive frequency inleft..right, solen(counts)equals the distinct device count. Advancingleftnever discards a needed event for any futureright' > rightbecause timestamps are non-decreasing (moment[right'] - moment[i] >= moment[right] - moment[i] > t). Therefore, the firstrightreachinglen(counts) >= kachieves the minimum possibleend_ts, and because every index< leftis> tminutes beforeright(so any valid window starting< leftwould have ended< right),user_events[left]is simultaneously the minimum possiblestart_ts. - How could high-frequency activity from a single account degrade memory or latency, and how would you guard against it? Although each event enters and leaves the deque once —
O(1)amortized time per event, meaning constant average work per event over the whole run — a bot firingm = 500,000events from2devices insidet = 1440minutes would keep allmevents in memory if stored raw. First, immediately stop storing events for any user who has already qualified. Second, collapse consecutive or same-device events: whether[end - t, end]containskdistinct devices depends only on each device's latest timestamp (and earliest timestamp inside the horizon ifstart_tsis needed), or you can store only thek <= 5most recently active distinct devices to detectend_tsinO(k)memory and query cold storage only for the tiny fraction of flagged users.
Follow-up questions
- How would you process an unbounded event stream with capped memory when records are partitioned by user ID?
- Why is advancing the left pointer monotonically guaranteed to find the earliest valid window without undercounting active devices?
- How could high-frequency activity from a single account degrade memory or latency, and how would you guard against it?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array