KatInterview

Merge Active Intervals from Multiple Time-Series Sensors

Greedy & IntervalsModel answer
MediumModel answerGreedy & Intervalsintervalstime-seriesintersection

Last updated

Parse sensor streams into continuous activity windows and find time ranges where all sensors are simultaneously active.

Problem

You're building a monitoring system that processes time-series data from multiple sensors. Each sensor generates readings as (timestamp, value) pairs sorted by timestamp, where timestamp is a non-negative integer and value is a float in [0.0, 1.0].

Your task is to identify all time windows during which every sensor is simultaneously reporting activity above a given threshold.

Active Interval Rules

For each individual sensor:

  1. A reading is active when value >= threshold
  2. Consecutive active readings form a continuous interval as long as the time gap between them is at most max_gap
  3. When the gap exceeds max_gap, close the current interval and start a new one
  4. An isolated active reading at time t creates the interval [t, t]
  5. Any inactive reading (value < threshold) immediately closes the current interval

Output

Return all time intervals [start, end] where all sensors are active simultaneously, sorted chronologically. Merge adjacent or overlapping intervals in the output.

Do not modify the input.

Function Signature

def find_shared_motion_periods(
    streams: list[list[tuple[int, float]]],
    threshold: float,
    max_gap: int
) -> list[tuple[int, int]]:
    pass

Constraints

  • 0 ≤ len(streams) ≤ 100
  • Each stream: 0 ≤ len(stream) ≤ 10⁴ readings
  • Timestamps strictly increasing: 0 ≤ timestamp ≤ 10⁹
  • 0.0 ≤ value ≤ 1.0
  • 0.0 ≤ threshold ≤ 1.0
  • 0 ≤ max_gap ≤ 10⁶

Examples

Example 1:

streams = [
    [(10, 0.8), (14, 0.9), (20, 0.7), (25, 0.2)],
    [(12, 0.6), (15, 0.8), (18, 0.9), (30, 0.9)]
]
threshold = 0.5
max_gap = 5

# Sensor 0: active at 10, 14, 20 (25 is below threshold)
#   Gap 14-10=4 ≤ 5 → interval [10,14]
#   Gap 20-14=6 > 5 → new interval [20,20]
#   Intervals: [10,14], [20,20]
#
# Sensor 1: active at 12, 15, 18, 30
#   Gaps: 3, 3, 12 → intervals [12,18], [30,30]
#
# Overlap: [10,14] ∩ [12,18] = [12,14]
# Result: [(12, 14)]

Example 2:

streams = [
    [(5, 0.8)],
    [(5, 0.9)]
]
threshold = 0.7
max_gap = 2

# Both sensors active at exactly t=5
# Result: [(5, 5)]

Hints

Hint 1

First convert each sensor stream into a list of disjoint intervals independently, then combine them

Hint 2

Use a two-pointer approach to intersect sorted interval lists—advance whichever interval ends first

Hint 3

Handle the edge case where all intervals from one sensor disappear; the answer is immediately empty