Merge Active Intervals from Multiple Time-Series Sensors
Greedy & IntervalsModel answerLast 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:
- A reading is active when
value >= threshold - Consecutive active readings form a continuous interval as long as the time gap between them is at most
max_gap - When the gap exceeds
max_gap, close the current interval and start a new one - An isolated active reading at time
tcreates the interval[t, t] - 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.00.0 ≤ threshold ≤ 1.00 ≤ 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Break the problem into two independent phases:
Phase 1: Extract Active Intervals Per Sensor
Process each sensor stream in a single pass, maintaining:
start: beginning of the current active interval (orNonewhen no interval is open)prev: most recent timestamp in the current interval
For each reading (t, value):
- If active (
value >= threshold):- If no interval is open, start one at
t - If an interval is open and
t - prev <= max_gap, extend it by updatingprev = t - If the gap exceeds
max_gap, close the current interval atprevand start a new one att
- If no interval is open, start one at
- If inactive: close any open interval immediately at
prev
At the end of the stream, close any remaining open interval.
Each sensor produces a sorted list of disjoint intervals.
Phase 2: Compute Multi-Way Intersection
Use a pairwise interval intersection algorithm and fold it across all sensors.
Two-pointer intersection of sorted interval lists A and B:
- Maintain pointers
iandj - For intervals
[a_start, a_end]and[b_start, b_end]:- Overlap exists when
max(a_start, b_start) <= min(a_end, b_end) - Emit
[max(a_start, b_start), min(a_end, b_end)] - Advance the pointer for whichever interval ends first (it cannot overlap future intervals in the other list)
- Overlap exists when
Apply this pairwise intersection iteratively: result = intervals[0], then result = intersect(result, intervals[1]), and so on. Stop early if result becomes empty.
Complexity
- Time: O(N) to extract intervals from all sensors (N = total readings), then O(k · M) to intersect k sensor interval lists, where M is the maximum interval count. Worst case O(k · N) ≈ 10⁸ operations at the constraint limits, but typically much faster due to early termination
- Space: O(N) for storing intervals
An alternative sweep-line approach sorting all interval endpoints runs in O(N log N) but adds complexity.
Edge Cases
- Empty sensor list → return
[] - Any sensor with no active readings → return
[] max_gap = 0: every active reading becomes an isolated[t, t]intervalthreshold = 0.0: all readings are active; gaps alone determine intervals- Single-point overlaps (e.g., both sensors active at exactly
t=5) → valid output[(5, 5)] - Boundary overlaps:
[10, 14]and[14, 20]→ intersection is[14, 14]
Common Mistakes
- Ignoring inactive readings: some candidates only look at gaps between active readings, missing that an explicit low-value reading should close the interval
- Off-by-one in gap comparison: use
t - prev <= max_gapto keep the interval open, not< - Skipping single-point overlaps: ensure
lo <= hi(not<) when checking overlap validity - Not handling empty streams early: attempting intersection when a sensor has no intervals wastes work
Code
def find_shared_motion_periods(
streams: list[list[tuple[int, float]]],
threshold: float,
max_gap: int
) -> list[tuple[int, int]]:
def extract_intervals(stream):
"""Convert a sensor stream into disjoint active intervals."""
intervals = []
start = prev = None
for t, value in stream:
if value >= threshold:
if start is None:
# Begin new interval
start = prev = t
elif t - prev <= max_gap:
# Extend current interval
prev = t
else:
# Gap too large; close and start new
intervals.append((start, prev))
start = prev = t
elif start is not None:
# Inactive reading closes interval
intervals.append((start, prev))
start = prev = None
# Close any remaining open interval
if start is not None:
intervals.append((start, prev))
return intervals
def intersect_intervals(a, b):
"""Find intersection of two sorted lists of disjoint intervals."""
i = j = 0
result = []
while i < len(a) and j < len(b):
lo = max(a[i][0], b[j][0])
hi = min(a[i][1], b[j][1])
if lo <= hi: # Valid overlap (includes single-point)
result.append((lo, hi))
# Advance whichever interval ends first
if a[i][1] < b[j][1]:
i += 1
else:
j += 1
return result
if not streams:
return []
# Start with first sensor's intervals
result = extract_intervals(streams[0])
# Intersect with each subsequent sensor
for stream in streams[1:]:
intervals = extract_intervals(stream)
result = intersect_intervals(result, intervals)
# Early termination if no overlap remains
if not result:
return []
return result
Verification
On Example 1:
- Sensor 0:
[(10, 14), (20, 20)] - Sensor 1:
[(12, 18), (30, 30)] - Intersection:
max(10,12)=12, min(14,18)=14→(12, 14)✓
On Example 2:
- Both sensors:
[(5, 5)] - Intersection:
max(5,5)=5, min(5,5)=5→(5, 5)✓