KatInterview

Merge Sensor Readings into Qualifying State Runs

Arrays & HashingAuto-graded · 16 test cases
MediumAuto-gradedArrays & Hashingrun-lengthsingle-passsimulation

Last 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 integer
  • state: 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 label
  • start_time: the timestamp of the first entry in the run
  • end_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_duration behaves 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

  • readings is sorted by timestamp (non-decreasing).
  • 0 <= len(readings) <= 10^5
  • All timestamps are non-negative integers.
  • Each entry has exactly the keys timestamp and state.

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.