KatInterview

Extract Continuous Active Time Windows

Greedy & IntervalsAuto-graded · 18 test cases
EasyAuto-gradedGreedy & Intervalsgreedy-intervalsarraystwo-pointers

Last updated

Process chronological sensor sample logs to extract continuous active periods matching a minimum elapsed duration requirement.

You are given a chronological sequence of system readings represented as a list of pairs [timestamp, state].

  • timestamp is a strictly increasing integer time value.
  • state is an integer indicating whether the system is active (1) or inactive (0).

A continuous active period consists of a uninterrupted sequence of 1 states. The time interval of an active period starts at the timestamp of the first 1 in the sequence and ends at the timestamp of the last 1 in that sequence.

The duration of an interval [t_start, t_end] is computed as t_end - t_start. Note that a sequence containing only a single active sample has t_start == t_end and a duration of 0.

Your goal is to extract all active time intervals whose total duration t_end - t_start is at least k time units (duration >= k).

Return the qualifying intervals as a list of [start_timestamp, end_timestamp] pairs in the order they occur.

Constraints

  • 0 <= len(samples) <= 10^5
  • Each element of samples is a list of two integers [timestamp, state].
  • Timestamps are strictly increasing integers.
  • state is either 0 or 1.
  • 0 <= k <= 10^9

Examples

Example 1

Input: get_active_intervals([[1, 1], [2, 1], [3, 0], [4, 1], [5, 1], [6, 1]], 2)

Output: [[4, 6]]

Example 2

Input: get_active_intervals([[1, 0], [5, 1]], 0)

Output: [[5, 5]]

Hints

Hint 1

Iterate through the samples maintaining tracking variables for the start timestamp and most recent timestamp of the current active run.

Hint 2

When encountering a zero or reaching the end of the list, compute the duration of the current active run (if one is open).

Hint 3

Make sure to evaluate and possibly append the final active run after the main loop finishes.