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) and10(0.92 > 0.6) form the first window[6, 10]. At second14,0.6equalsthresholdand is therefore quiet, ending that window. Second19stays quiet, and the final sample at second28(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
0and50both exceed1.0with 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
readingsis a two-element list[timestamp, intensity]wheretimestamprepresents an integer second (possibly typed as a whole-numberfloatinList[List[float]]) andintensityis a finitefloat. - Timestamps are strictly ascending across
readings(readings[i][0] < readings[i + 1][0]), and timestamps as well asintensityandthresholdmay be negative, zero, or positive.
Step-by-step walkthrough
Understand the rules and the threshold boundary
We receive a chronologically ordered list
readingsof[timestamp, intensity]pairs and a cutoffthreshold, 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 whenmotion_level > threshold. Whenevermotion_level <= threshold(including exact tiesmotion_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 second28has 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]Why brute-force slice checking and pre-filtering fail
Two tempting beginner shortcuts go wrong for different reasons: - Checking every subarray
(i, j): Testing allO(n^2)slicesreadings[i : j + 1]to verify that every sample inside exceedsthresholdand neither neighbor exceedsthresholdworks as a small-input test oracle, but re-scans elements up toO(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.
Model the sensor as a two-state stopwatch
Imagine holding a stopwatch with two variables while scanning
readingsfrom left to right: -run_start: the integer timestamp where the current active burst began, orNonewhen 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 Nonerather thanif not run_start:. Timestamp0(as in Example 2) is a valid integer timestamp, andbool(0)isFalsein Python! - Converttimestamp = int(raw_time)when unpacking[raw_time, motion_level]. Because the input parameter is typedList[List[float]]while the return type isList[List[int]], casting guarantees integer endpoints even if timestamps arrive as whole-number floats like6.0.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
readingsis active (like[28, 0.85]in Example 1)? Then the loop finishes while the state machine is stillACTIVE, because no trailing quiet sample arrived to close it! Oneif run_start is not Nonecheck 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 intervalsTrace 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]]withthreshold = 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
readingsis already ordered by strictly ascending timestamps, completed windows are appended in chronological order automatically without any sorting pass.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 thensamples once from left to right, doing one float comparison (motion_level > threshold), at most two scalar assignments, and at most oneO(1)amortized listappendper sample. - Space:
O(1)auxiliary space (O(k)including output). Outside the returnedintervalslist, we maintain only scalar variables (run_start,run_end,timestamp,is_active).
Edge cases
- Empty log (
readings = []): The loop executes zero iterations,run_startstaysNone, 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 to14. - Single triggered sample (
[[7, 1.0]]withthreshold = 0.5): Bothrun_startandrun_endbecome7, returning the point window[[7, 7]]. - Triggered run still open at the end of
readings: Flushed by the post-loopif run_start is not Noneguard so[28, 28]in Example 1 is never lost. - Run starting at timestamp
0or negative timestamps: Because0is falsy in Python, testingif run_start is None:(neverif not run_start:) prevents a window opened att = 0in Example 2 from havingrun_startoverwritten 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]]): Castingint(raw_time)guarantees the returned windows hold Pythonintvalues matchingList[List[int]].
Common mistakes
- Using
>=instead of>: Treatingintensity == thresholdas 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
readingsnever 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; updatingrun_endon each triggered sample avoids this off-by-one mistake. - Writing
if not run_start:instead ofif run_start is None:: When a window opens attimestamp = 0(Example 2),not 0isTrue, so the next triggered sample at50overwritesrun_start = 50and drops0.
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, andrun_endinside a smallSensorWindowTrackerclass whoseon_sample(timestamp, intensity)method returns[start, end]whenever a quiet sample closes an open run (andNoneotherwise), paired with aflush()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: whenrun_start is not None and timestamp - run_end > max_gap, append[run_start, run_end]immediately and start a fresh window withrun_start = timestampbefore updatingrun_end = timestamp. Runtime staysO(n)and auxiliary space staysO(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_thresholdto open a window and a lowerexit_thresholdto close it, just like a room thermostat), or merge consecutive windows separated by fewer thancooldown_secondsin a lightweight post-pass so brief dips do not splinter one physical event into many tiny clips.
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?
- What change is needed if two adjacent active readings separated by more than max_gap seconds must be split into distinct intervals?
- How can a motion detector avoid rapid on-off chatter when readings fluctuate right around the threshold?
Similar questions
- Extract and Unify Camera Alert Windows
- Find the User Reaching All Cameras via Transitive Group Membership
- Universal Camera Access Accounts
- Full-Access Camera Admins Across Nested Groups
- LRU Cache Simulation and Fewest Coins
- Design O(1) LRU and LFU In-Memory Caches
- Simultaneous High-Motion Intervals Across Camera Feeds
More Verkada interview questions
- Camera Log Ingestion and Query API Server Medium
- Fleet-Scale Security Camera Liveness and Offline Monitoring Medium
- Find the User Reaching All Cameras via Transitive Group Membership Medium Pro
- Design O(1) LRU and LFU In-Memory Caches Medium Pro
- Score Letter Feedback for Word Guesses Hard Pro
- Simultaneous High-Motion Intervals Across Camera Feeds Hard Pro
- Constant-Memory Generator Parser for Quoted Key-Value Logs Medium Pro
- Filterable Camera Dashboard Medium Pro
- Camera Fleet Health Monitoring Medium Pro
- Hierarchical Camera Authorization Service Hard Pro