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 >= X qualify; any record with amount_cents < X is ignored.
  • Deduplication: Exact duplicate records—having the same user_id, device_id, UTC instant, and amount_cents—must be treated as a single event.
  • Out-of-order arrivals & timezones: Records may arrive up to 5 minutes 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 when end_utc - start_utc <= t minutes.
  • Earliest qualifying window & output format: Return one dictionary per qualifying user (ordered by user_id ascending) containing:
    • "user_id": the integer user_id,
    • "start_ts": the original ts string of the earliest event in that user's earliest qualifying window,
    • "end_ts": the original ts string of the event that first brings the window to k distinct devices, and
    • "device_ids": the k distinct device_id strings 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^6
  • k in {3, 4, 5}
  • 0 <= t <= 1440
  • X >= 0
  • Arrival timestamps may be out of order by up to 5 minutes.
  • Target O(n log n) total time complexity and O(m) active window state, where m is the maximum number of events for a single user within t minutes.

Step-by-step walkthrough

  1. 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 least k qualifying events (amount_cents >= X) from k different devices whose timestamps all fit within t minutes of each other.

    Let's pin down the exact rules confirmed by the statement and samples:

    • Amount filter (amount_cents >= X): transfers strictly below X are ignored completely (in Example 3, 999 < 1000 does not count). Transfers equal to X count.
    • Deduplication: exact duplicate events (same user_id, device_id, UTC instant, and amount_cents) are ignored.
    • Inclusive t-minute span: a window [start_ts, end_ts] is valid when end_moment - start_moment <= t minutes.
    • 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 reach k distinct devices.
    • UTC comparison: events can arrive up to 5 minutes out of order and carry Z or timezone offsets like -05:00, so we convert timestamps to UTC instants and sort per user before scanning.
  2. 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 left as the window start and walks right forward until either k distinct devices appear or right is more than t minutes past left.

    Why does that miss the O(n log n) requirement? Suppose one active user has m events packed inside t minutes from only k - 1 devices. Starting from left = 0 scans m events, starting from left = 1 scans m - 1 events, and so on — O(n * m) work overall, which approaches 10^12 steps when n = 10^6.

  3. Key idea: two-pointer sliding window with per-device counts

    Notice that as right moves forward to a newer timestamp, the cutoff moment_right - t minutes also moves forward — so any old event that fell out of the window for right can never fit in the window for right + 1!

    That means both left and right only ever move forward. Inside user_events[left..right], we track counts[device_id] — how many events inside the current window belong to each device, deleting a key whenever its count drops to 0 so len(counts) is always the number of distinct devices in O(1) time.

    Why do we need a count per device instead of a plain set? Look at k = 3, t = 10 on a@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 right where len(counts) >= k guarantees:

    1. Earliest end_ts: no valid k-device set ended earlier, or a smaller right would already have had len(counts) >= k.
    2. Earliest start_ts: every event before left is more than t minutes before right, so any k-device set starting before left would have had to end strictly before right (impossible by point 1).
    3. Exact k devices: one step earlier len(counts) was at most k - 1, and adding user_events[right] adds at most 1 new device, so len(counts) is exact k.
  4. 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 datetime gives continuous elapsed time immune to daylight-saving transitions. While grouping by user_id, we immediately skip amount < X and drop exact duplicates via a seen set, keeping the original ts string 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_user
    
  5. Write the sliding-window sweep

    In find_earliest_window, each event enters the window once when right visits it and leaves at most once when left advances past it:

    • Notice while moment - user_events[left][0] > max_span: uses strict >: if two events are exact t minutes apart, > is False, keeping both inside the closed [start_ts, end_ts] window. Also, when left == right, the difference is 0 <= max_span, so left never runs past right even when t = 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
    
  6. Sort per user and assemble the output

    For each user_id in sorted order, user_events.sort() orders (moment, device_id, ts) chronologically (breaking same-second ties deterministically by device_id), repairing any <= 5-minute out-of-order arrivals. Once (left, right) is found, devices_in_order collects the k distinct device_ids in order of first appearance using a seen_devices set for O(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 results
    
  7. Walk 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: []
    
  8. 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} (2 distinct devices).
  • When c@12 arrives, a@0 is 12 > 10 minutes old, so left moves to b@3 and counts['a'] drops from 2 to 1 (device a stays counted thanks to a@9!).
  • Now counts is {a: 1, b: 1, c: 1} (3 distinct devices), so we stop immediately and report [3, 12] with devices ['b', 'a', 'c'].

Complexity

  • Time: O(n log n), where n is the total number of input events. Parsing timestamps, filtering amount >= X, and deduplicating with seen do O(1) expected hash-table work per event (O(n) total); sorting each user u's n_u events takes O(n_u log n_u), which sums across all users to at most O(n log n); and in find_earliest_window both left and right only advance, so every event enters and leaves counts at most once in O(n_u) time.
  • Space: O(n) in batch mode (O(m) for the active window itself), where m is the maximum events of one user within a t-minute horizon. Because the judge passes an arbitrary unpartitioned list events, grouping and deduplicating across all users stores up to n qualifying events, whereas counts inside the sweep holds at most m active devices (and streaming per user bounds total memory per user to O(m), as detailed in the first follow-up).

Edge cases

  • Empty input or all amounts below X: by_user has no qualifying windows and returns []; amounts equal to X qualify.
  • Repeated events from one device (Example 3): d1@09:00 and d1@09:02 increment counts['d1'] to 2, contributing only 1 distinct device toward k.
  • Exact duplicate events: dropped by seen using (user_id, device_id, utc_moment, amount).
  • Inclusive window boundary (end - start == t minutes) and t = 0: strict > in moment - user_events[left][0] > max_span keeps events exact t minutes apart, and when t = 0 it requires k distinct devices at the exact same timestamp without ever pushing left past right.
  • 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: 3 transfers from the same phone are 1 device, not 3.
  • Using a set instead of a reference-counted dictionary: deleting old_device from a set when user_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 though 01:59-05:00 is 06:59Z (one minute later).
  • Filtering amount >= X too late: letting < X events enter the window inflates len(counts) (in Example 3, d2's 999-cent transfer would falsely complete 3 devices).
  • 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 right reaching k devices.

Alternative approaches

  • Per-start forward scan (O(n * m) time): for each left, scan right forward up to t minutes collecting distinct devices. Simple to verify on tiny test cases, but quadratic when m is large.
  • Minute-bucket ring buffer: when timestamps are rounded to whole minutes, maintain t + 1 per-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 incoming amount >= X events in a min-heap (a priority queue ordered by earliest timestamp first) plus a small deduplication set for those <= 5 minutes 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 supporting O(1) appends on the right and pops from the left) with the exact same counts dictionary. Once a user triggers len(counts) >= k, mark them reported and discard their buffers, bounding each active user's memory to O(m) events over at most t + 5 minutes.
  • Why is advancing the left pointer monotonically guaranteed to find the earliest valid window without undercounting active devices? Maintain the loop invariant after each right step: user_events[left..right] holds all events in 0..right within t minutes of user_events[right], and counts maps each active device_id to its exact positive frequency in left..right, so len(counts) equals the distinct device count. Advancing left never discards a needed event for any future right' > right because timestamps are non-decreasing (moment[right'] - moment[i] >= moment[right] - moment[i] > t). Therefore, the first right reaching len(counts) >= k achieves the minimum possible end_ts, and because every index < left is > t minutes before right (so any valid window starting < left would have ended < right), user_events[left] is simultaneously the minimum possible start_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 firing m = 500,000 events from 2 devices inside t = 1440 minutes would keep all m events 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] contains k distinct devices depends only on each device's latest timestamp (and earliest timestamp inside the horizon if start_ts is needed), or you can store only the k <= 5 most recently active distinct devices to detect end_ts in O(k) memory and query cold storage only for the tiny fraction of flagged users.

Follow-up questions

Similar questions

More Gemini interview questions

All 1 Gemini questions →