Detect Contiguous Active Sensor Windows

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

Given a chronologically ordered log readings of sensor samples [timestamp, intensity] and a numeric cutoff threshold, identify every longest uninterrupted run of triggered samples and report each run's [first_timestamp, last_timestamp] window.

Apply the following rules when grouping samples: - A sample is triggered strictly when intensity > threshold; any sample with intensity <= threshold (including exact equality intensity == threshold) is quiet and belongs to no window. - Grouping depends purely on index adjacency inside readings: two triggered samples with no quiet sample between them stay inside the same window regardless of how many seconds separate their timestamps. - A triggered sample with no triggered neighbors on either side produces a zero-duration window [t, t]. - Return the resulting [first_timestamp, last_timestamp] pairs of int timestamps in ascending chronological order (or [] when no sample exceeds threshold).

def find_motion_intervals(readings: List[List[float]], threshold: float) -> List[List[int]]:

Examples

Example 1

  • Input: readings = [[2, 0.3], [6, 0.75], [10, 0.92], [14, 0.6], [19, 0.4], [28, 0.85]], threshold = 0.6
  • Output: [[6, 10], [28, 28]]
  • Explanation: Samples at seconds 6 (0.75 > 0.6) and 10 (0.92 > 0.6) form the first window [6, 10]. At second 14, 0.6 equals threshold and is therefore quiet, ending that window. Second 19 stays quiet, and the final sample at second 28 (0.85 > 0.6) forms the single-point window [28, 28].

Example 2

  • Input: readings = [[0, 1.5], [50, 2.1], [55, 0.9]], threshold = 1.0
  • Output: [[0, 50]]
  • Explanation: Seconds 0 and 50 both exceed 1.0 with no quiet sample in between, so they merge into [0, 50] despite the 50-second clock gap, before [55, 0.9] ends the run.

Constraints

  • 0 <= len(readings) <= 10^5
  • Every entry in readings is a two-element list [timestamp, intensity] where timestamp represents an integer second (possibly typed as a whole-number float in List[List[float]]) and intensity is a finite float.
  • Timestamps are strictly ascending across readings (readings[i][0] < readings[i + 1][0]), and timestamps as well as intensity and threshold may be negative, zero, or positive.

Step-by-step walkthrough

  1. Understand the rules and the threshold boundary

    We receive a chronologically ordered list readings of [timestamp, intensity] pairs and a cutoff threshold, and we need to report [start_time, end_time] for every maximal stretch of consecutive active samples.

    Before writing code, lock down three rules from the specification: 1. Strict inequality (>): A sample is active only when motion_level > threshold. Whenever motion_level <= threshold (including exact ties motion_level == threshold), the sample is inactive. 2. Array adjacency decides grouping, not clock gaps: Two active samples at neighboring array indices stay in the same window even if their timestamps are [0, 1.5] and [50, 2.1] (Example 2). Only an inactive sample between them closes the window. 3. Isolated active samples form point windows: If a single active sample at second 28 has no active neighbors, its opening and closing timestamps coincide, producing [28, 28].

    Index:     0         1          2          3         4         5
    Sample:  [2,0.3]  [6,0.75]  [10,0.92]  [14,0.6]  [19,0.4]  [28,0.85]
    > 0.6?     no        YES        YES     no (==)     no        YES
                         |--- [6, 10] ---|                      [28,28]
    
  2. Why brute-force slice checking and pre-filtering fail

    Two tempting beginner shortcuts go wrong for different reasons: - Checking every subarray (i, j): Testing all O(n^2) slices readings[i : j + 1] to verify that every sample inside exceeds threshold and neither neighbor exceeds threshold works as a small-input test oracle, but re-scans elements up to O(n^3) times. - Filtering to active samples first: Running [r for r in readings if r[1] > threshold] first erases the quiet samples that separated distinct bursts! In Example 1, [6, 0.75], [10, 0.92], and [28, 0.85] would look adjacent after filtering and collapse into one bogus [6, 28] window.

    To preserve the separators without rescanning, inspect every sample once in order and remember whether an active run is currently open.

  3. Model the sensor as a two-state stopwatch

    Imagine holding a stopwatch with two variables while scanning readings from left to right: - run_start: the integer timestamp where the current active burst began, or None when idle. - run_end: the integer timestamp of the most recent active sample in the current burst.

                 motion_level <= threshold (stay idle)
                             +------+
                             |      v
                          +------------+
                          |    IDLE    |  run_start = None, run_end = None
                          +------------+
                            |        ^
       motion_level >       |        |  motion_level <= threshold
       threshold            |        |  append [run_start, run_end]
       run_start = t        v        |  reset to None
       run_end   = t      +------------+
                          |   ACTIVE   |  run_start != None
                          +------------+
                            |        ^
                            +--------+
                    motion_level > threshold
                    run_end = t (extend!)
    

    Two defensive details protect us from subtle Python bugs: - Always test run_start is None rather than if not run_start:. Timestamp 0 (as in Example 2) is a valid integer timestamp, and bool(0) is False in Python! - Convert timestamp = int(raw_time) when unpacking [raw_time, motion_level]. Because the input parameter is typed List[List[float]] while the return type is List[List[int]], casting guarantees integer endpoints even if timestamps arrive as whole-number floats like 6.0.

  4. Scan readings and flush the final open run

    Inside the loop, an inactive sample closes any open burst. What if the very last sample in readings is active (like [28, 0.85] in Example 1)? Then the loop finishes while the state machine is still ACTIVE, because no trailing quiet sample arrived to close it! One if run_start is not None check right after the loop flushes that trailing window.

    def find_motion_intervals(readings: List[List[float]], threshold: float) -> List[List[int]]:
        # intervals: list of [start_time, end_time] integer pairs for completed active runs
        intervals: List[List[int]] = []
        # run_start: int timestamp of the first active reading in the open run, or None when idle
        run_start: Optional[int] = None
        # run_end: int timestamp of the most recent active reading in the open run
        run_end: Optional[int] = None
    
        # Phase 1: Sweep left to right across time-sorted readings, maintaining at most one open run.
        for raw_time, motion_level in readings:
            # Input type is List[List[float]], so cast whole-number timestamps to int for List[List[int]].
            timestamp = int(raw_time)
            # Strict `>` is required: a reading with motion_level == threshold is inactive.
            is_active = motion_level > threshold
    
            if is_active:
                # Check `is None` (never `if not run_start`) because timestamp 0 is valid but falsy.
                if run_start is None:
                    run_start = timestamp
                run_end = timestamp
            elif run_start is not None:
                # An inactive reading immediately closes the open active run.
                intervals.append([run_start, run_end])
                run_start = None
                run_end = None
    
        # Phase 2: Flush any active run that was still open when the input ended.
        if run_start is not None and run_end is not None:
            intervals.append([run_start, run_end])
    
        return intervals
    
  5. Trace Example 1 step by step

    Walk readings = [[2, 0.3], [6, 0.75], [10, 0.92], [14, 0.6], [19, 0.4], [28, 0.85]] with threshold = 0.6:

    timestamp  level  > 0.6?  transition                  run_start  run_end  intervals
    ---------  -----  ------  --------------------------  ---------  -------  -------------------
    2          0.30   False   stay IDLE                   None       None     []
    6          0.75   True    IDLE -> ACTIVE (open)       6          6        []
    10         0.92   True    ACTIVE -> ACTIVE (extend)   6          10       []
    14         0.60   False   ACTIVE -> IDLE (close!)     None       None     [[6, 10]]
    19         0.40   False   stay IDLE                   None       None     [[6, 10]]
    28         0.85   True    IDLE -> ACTIVE (open)       28         28       [[6, 10]]
    (after loop)      --      flush open run              --         --       [[6, 10], [28, 28]]
    

    Because readings is already ordered by strictly ascending timestamps, completed windows are appended in chronological order automatically without any sorting pass.

  6. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def find_motion_intervals(readings: List[List[float]], threshold: float) -> List[List[int]]:
        # intervals: list of [start_time, end_time] integer pairs for completed active runs
        intervals: List[List[int]] = []
        # run_start: int timestamp of the first active reading in the open run, or None when idle
        run_start: Optional[int] = None
        # run_end: int timestamp of the most recent active reading in the open run
        run_end: Optional[int] = None
    
        # Phase 1: Sweep left to right across time-sorted readings, maintaining at most one open run.
        for raw_time, motion_level in readings:
            # Input type is List[List[float]], so cast whole-number timestamps to int for List[List[int]].
            timestamp = int(raw_time)
            # Strict `>` is required: a reading with motion_level == threshold is inactive.
            is_active = motion_level > threshold
    
            if is_active:
                # Check `is None` (never `if not run_start`) because timestamp 0 is valid but falsy.
                if run_start is None:
                    run_start = timestamp
                run_end = timestamp
            elif run_start is not None:
                # An inactive reading immediately closes the open active run.
                intervals.append([run_start, run_end])
                run_start = None
                run_end = None
    
        # Phase 2: Flush any active run that was still open when the input ended.
        if run_start is not None and run_end is not None:
            intervals.append([run_start, run_end])
    
        return intervals
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture an operator watching a live sensor dial with a clipboard: as long as the dial stays at or below threshold, nothing is logged. The instant a sample climbs strictly above threshold, the operator jots down that timestamp as run_start and keeps updating run_end on each subsequent triggered sample; the moment a quiet sample (<= threshold) arrives, the operator records [run_start, run_end] on the clipboard and resets to idle. Formally, this is a two-state machine (a loop that sits in either an "idle" mode or an "open run" mode and transitions on each input) that extracts every maximal contiguous run (a slice of consecutive triggered elements that cannot grow left or right without hitting a quiet element or an array boundary).

Why do simpler-looking shortcuts fail? Checking every candidate subarray readings[i : j + 1] repeats comparisons across overlapping slices in O(n^3) time (or O(n^2) with incremental checks). Conversely, filtering out quiet samples upfront ([r for r in readings if r[1] > threshold]) erases the quiet separators between distinct events — in Example 1, [6, 10] and [28, 28] would appear adjacent after filtering and merge into one false [6, 28] window!

Let's trace Example 1 (threshold = 0.6) on [[2, 0.3], [6, 0.75], [10, 0.92], [14, 0.6], [19, 0.4], [28, 0.85]]:

[2,  0.30] -> 0.30 <= 0.6 (quiet)     -> stay idle
[6,  0.75] -> 0.75 >  0.6 (triggered) -> open run:   run_start = 6,  run_end = 6
[10, 0.92] -> 0.92 >  0.6 (triggered) -> extend run: run_start = 6,  run_end = 10
[14, 0.60] -> 0.60 <= 0.6 (quiet)     -> close run!  emit [6, 10], reset to idle
[19, 0.40] -> 0.40 <= 0.6 (quiet)     -> stay idle
[28, 0.85] -> 0.85 >  0.6 (triggered) -> open run:   run_start = 28, run_end = 28
(end of log)                          -> flush open run! emit [28, 28]

Final output: [[6, 10], [28, 28]]

Complexity

Let n be the number of samples in readings and k be the number of returned windows (k <= (n + 1) // 2, because at least one quiet sample must separate any two windows).

  • Time: O(n). We scan the n samples once from left to right, doing one float comparison (motion_level > threshold), at most two scalar assignments, and at most one O(1) amortized list append per sample.
  • Space: O(1) auxiliary space (O(k) including output). Outside the returned intervals list, we maintain only scalar variables (run_start, run_end, timestamp, is_active).

Edge cases

  • Empty log (readings = []): The loop executes zero iterations, run_start stays None, and [] is returned.
  • Intensity exactly equal to threshold: Treated as quiet because the trigger rule is strictly >. In Example 1 (threshold = 0.6), [14, 0.6] closes the [6, 10] window rather than extending it to 14.
  • Single triggered sample ([[7, 1.0]] with threshold = 0.5): Both run_start and run_end become 7, returning the point window [[7, 7]].
  • Triggered run still open at the end of readings: Flushed by the post-loop if run_start is not None guard so [28, 28] in Example 1 is never lost.
  • Run starting at timestamp 0 or negative timestamps: Because 0 is falsy in Python, testing if run_start is None: (never if not run_start:) prevents a window opened at t = 0 in Example 2 from having run_start overwritten on the next sample.
  • Wide timestamp gaps between adjacent triggered samples ([[0, 1.5], [50, 2.1]]): Grouped into one window [[0, 50]] because index adjacency — not elapsed clock time — defines continuity.
  • Float-typed whole-number timestamps ([[0.0, 0.9], [5.0, 0.9]]): Casting int(raw_time) guarantees the returned windows hold Python int values matching List[List[int]].

Common mistakes

  • Using >= instead of >: Treating intensity == threshold as triggered violates the boundary rule and turns Example 1's [6, 10] into [6, 14].
  • Forgetting the post-loop flush: Any run that stays active through the final element of readings never hits a quiet sample inside the loop and is silently dropped without the trailing check.
  • Recording the quiet sample's timestamp as end_time: A window ends at its last triggered sample (10), not at the quiet sample (14) that closed it; updating run_end on each triggered sample avoids this off-by-one mistake.
  • Writing if not run_start: instead of if run_start is None:: When a window opens at timestamp = 0 (Example 2), not 0 is True, so the next triggered sample at 50 overwrites run_start = 50 and drops 0.

Follow-up questions

  • How would you refactor this function into an online tracker when readings arrive one at a time from a live sensor feed? Turn the loop variables into an online algorithm (an algorithm that processes one arriving item at a time in constant memory without storing past inputs): encapsulate threshold, run_start, and run_end inside a small SensorWindowTracker class whose on_sample(timestamp, intensity) method returns [start, end] whenever a quiet sample closes an open run (and None otherwise), paired with a flush() method invoked on stream shutdown or segment rollover.
  • What change is needed if two adjacent active readings separated by more than max_gap seconds must be split into distinct intervals? Add one check inside the if is_active: branch: when run_start is not None and timestamp - run_end > max_gap, append [run_start, run_end] immediately and start a fresh window with run_start = timestamp before updating run_end = timestamp. Runtime stays O(n) and auxiliary space stays O(1).
  • How can a motion detector avoid rapid on-off chatter when readings fluctuate right around the threshold? Real sensors apply hysteresis (using two cutoffs instead of one: a higher enter_threshold to open a window and a lower exit_threshold to close it, just like a room thermostat), or merge consecutive windows separated by fewer than cooldown_seconds in a lightweight post-pass so brief dips do not splinter one physical event into many tiny clips.

Follow-up questions

Similar questions

More Verkada interview questions

All 21 Verkada questions →