Merge Sensor Readings into Qualifying State Runs
Arrays & HashingAuto-graded · 16 test casesLast updated
Group consecutive identical-state readings into runs, then keep only runs whose last-minus-first timestamp span meets a minimum threshold.
Merge Sensor Readings into Qualifying State Runs
A device logs its status over time. Each log entry is a dictionary with two keys:
timestamp: a non-negative integerstate: a string label such as"ACTIVE","IDLE"or"ERROR"
The entries are already ordered by timestamp.
A run is a maximal block of adjacent entries that all share the same state. Each run is described by:
state: the shared labelstart_time: the timestamp of the first entry in the runend_time: the timestamp of the last entry in the run (not the first entry of the following run)
The span of a run is end_time - start_time.
Implement a function that scans the log and returns every run whose span is greater than or equal to a given threshold.
Function
Take a list of entries readings and an integer min_duration. Return a list of dictionaries, each of the form {"state": ..., "start_time": ..., "end_time": ...}.
Rules
- Runs must be contiguous. If a state appears, then changes, then appears again, those are separate runs.
- Return the runs in chronological order (the order in which they occur in the input).
- A run made of a single entry has span 0, so it is returned only when
min_duration <= 0. - An empty input returns an empty list.
- A negative
min_durationbehaves the same as 0, so every run is returned. - The span only depends on the first and last timestamps of the run. Entries with duplicate timestamps cause no special handling.
Constraints
readingsis sorted bytimestamp(non-decreasing).0 <= len(readings) <= 10^5- All timestamps are non-negative integers.
- Each entry has exactly the keys
timestampandstate.
Examples
Example 1
Input: extract_state_runs([{'timestamp': 1, 'state': 'A'}, {'timestamp': 2, 'state': 'A'}, {'timestamp': 3, 'state': 'B'}, {'timestamp': 4, 'state': 'B'}, {'timestamp': 5, 'state': 'B'}], 2)
Output: [{'state': 'B', 'start_time': 3, 'end_time': 5}]
Hints
Hint 1
Think of this as run-length grouping: walk through the list once and remember the state, first timestamp and latest timestamp of the run currently being built.
Hint 2
When the state of the next entry differs from the current run's state, the current run is finished. Check its span against the threshold, then begin a new run at that entry.
Hint 3
A run only gets closed when a state change occurs, so the very last run is never closed inside the loop. Remember to check and add it after the loop, and handle the empty list first.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a run-length grouping problem solved in one pass. While scanning, keep three values describing the run currently being built: its state, the timestamp of its first entry, and the timestamp of its latest entry.
For each subsequent entry:
- If its state equals the current run's state, the run continues.
- If its state differs, the current run is over. If its span (
run_end - run_start) is at leastmin_duration, append it to the result. Then start a new run whose state and start time come from this entry. - In both cases, update
run_endto this entry's timestamp, since it is the most recent entry of the (possibly new) run.
After the loop, the final run has not been closed by any state change, so apply the same check and append it if it qualifies. An empty input returns [] immediately.
Why it is correct
At the start of each iteration, the tracked values describe the maximal contiguous run ending at the previous entry. This holds initially (a run consisting of the first entry) and is preserved: an entry with the same state extends the run, while a different state ends it exactly at the point where a maximal run must end. So every maximal run is examined exactly once, in chronological order, and end_time is always the timestamp of the run's own last entry. A state that reappears later starts a new run, matching the contiguity rule. Single-entry runs have span 0 and pass only when min_duration <= 0, as required.
Complexity
- Time: O(n), with O(1) work per entry.
- Space: O(1) auxiliary, aside from the output list, which can hold up to n runs.
Reference solution
from typing import Dict, List
def extract_state_runs(readings: List[Dict], min_duration: int) -> List[Dict]:
result = []
if not readings:
return result
cur_state = readings[0]["state"]
run_start = readings[0]["timestamp"]
run_end = run_start
for i in range(1, len(readings)):
ts = readings[i]["timestamp"]
st = readings[i]["state"]
if st != cur_state:
if run_end - run_start >= min_duration:
result.append({"state": cur_state, "start_time": run_start, "end_time": run_end})
cur_state = st
run_start = ts
run_end = ts
if run_end - run_start >= min_duration:
result.append({"state": cur_state, "start_time": run_start, "end_time": run_end})
return result