KatInterview

Activity Windows from Sensor Readings Over a Cutoff

Arrays & HashingAuto-graded · 16 test cases
EasyAuto-gradedArrays & Hashingarraystwo-pointersintervals

Last updated

Scan sorted timestamped sensor readings once and group consecutive readings strictly above a cutoff into [first_time, last_time] windows.

Activity Windows from Sensor Readings Over a Cutoff

A motion sensor logs a series of readings. Each reading is a pair [timestamp, intensity], where timestamp is an integer number of seconds and intensity is a real number. The readings are given in strictly increasing order of timestamp.

Given a cutoff value, a reading is called hot if its intensity is strictly greater than cutoff. A reading whose intensity is less than or equal to cutoff is cold.

Group the readings into runs: a run is a maximal block of readings that are next to each other in the input list and are all hot. Adjacency is judged by position in the list only. Large differences between timestamps inside a run do not split it, and a cold reading always ends the run.

For each run, produce a window [start, end], where start is the timestamp of the first reading in the run and end is the timestamp of the last reading in the run. A run with just one reading yields a window with start == end.

Return all windows as a list, in the same order as they occur in the input.

Function

Implement find_hot_windows(readings, cutoff):

  • readings: a list of [timestamp, intensity] pairs, sorted by strictly increasing timestamp.
  • cutoff: a real number.
  • Returns a list of [start, end] integer pairs. If no reading is hot (or the input is empty), return an empty list.

Notes

  • The comparison is strict: an intensity exactly equal to cutoff is not hot, and it separates the runs on either side of it.
  • Follow this written rule exactly when deciding which readings are hot.

Constraints

  • 0 <= len(readings) <= 10^5
  • Timestamps are integers and strictly increasing.
  • Intensities and cutoff are real numbers (may be negative or fractional).
  • Each window is a two-element list [start, end] with start <= end.

Examples

Example 1

Input: find_hot_windows([[1, 0.4], [5, 0.2], [11, 0.9], [15, 0.9], [17, 0.8], [25, 0.5], [27, 0.8], [36, 0.9]], 0.8)

Output: [[11, 15], [36, 36]]

Hints

Hint 1

You only need to remember whether a run is currently open and, if so, when it began and the timestamp of the latest hot reading in it.

Hint 2

When you meet a cold reading while a run is open, record the window using the last hot timestamp (not the cold reading's timestamp), then reset the state.

Hint 3

The input might end while a run is still open, so after the loop you must record that last run too.