Simultaneous Active Windows Across Camera Feeds
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A facility operates multiple motion-sensing cameras. Every camera emits a chronological sequence of (timestamp, intensity) observations, where timestamp is a strictly increasing non-negative integer and intensity is a floating-point score in [0.0, 1.0] measuring detected movement.
Given sensor feeds streams, a minimum activation score threshold, and a tolerated silence window max_gap, compute the time spans during which every feed is active at once by implementing two functions:
from typing import List, Tuple
def active_intervals(
stream: List[Tuple[int, float]],
threshold: float,
max_gap: int,
) -> List[Tuple[int, int]]:
...
def find_shared_motion_periods(
streams: List[List[Tuple[int, float]]],
threshold: float,
max_gap: int,
) -> List[Tuple[int, int]]:
...
Rules
-
Per-feed active windows (
active_intervals):- An observation
(timestamp, intensity)counts as active wheneverintensity >= threshold. Observations strictly belowthresholdare ignored completely (they neither start windows nor affect time differences between active observations). - Two consecutive active observations on the same feed at
t_prevandt_currstay within the same continuous closed window[start, end]whent_curr - t_prev <= max_gap. Whenevert_curr - t_prev > max_gap, the current window ends att_prevand a fresh window opens att_curr. - A single active observation with no neighboring active observation within
max_gapforms a zero-length closed window(t, t). - Return the resulting disjoint closed
(start, end)tuples in ascending chronological order.
- An observation
-
All-feed shared windows (
find_shared_motion_periods):- Return every maximal closed interval
(start, end)during which every feed instreamsis active simultaneously, sorted in chronological order. - Instantaneous overlaps of the form
(t, t)are valid whenever every feed covers timestampt. - Any overlapping or endpoint-touching shared intervals must be coalesced into maximal closed intervals (though discrete points separated by an uncovered gap, such as
(5, 5)and(6, 6)whenmax_gap == 0, remain distinct). - If
streamsis empty (0feeds), return[]. - Leave
streamsand all inner lists unmodified.
- Return every maximal closed interval
Examples
Example 1
streams = [
[(2, 0.75), (5, 0.20), (6, 0.85), (13, 0.90), (16, 0.60)],
[(4, 0.70), (8, 0.95), (15, 0.80), (22, 0.90)],
]
threshold = 0.6
max_gap = 4
Output:
[(4, 6), (15, 15)]
Walk-through:
- Feed 0 keeps active timestamps 2, 6, 13, 16 ((5, 0.20) falls below 0.6 and is skipped, while (16, 0.60) meets >= 0.6). Because 6 - 2 = 4 <= 4, 13 - 6 = 7 > 4, and 16 - 13 = 3 <= 4, active_intervals(streams[0], 0.6, 4) returns [(2, 6), (13, 16)].
- Feed 1 keeps 4, 8, 15, 22. With 8 - 4 = 4 <= 4, 15 - 8 = 7 > 4, and 22 - 15 = 7 > 4, active_intervals(streams[1], 0.6, 4) returns [(4, 8), (15, 15), (22, 22)].
- Intersecting both lists yields (4, 6) from [2, 6] ∩ [4, 8] and (15, 15) from [13, 16] ∩ [15, 15].
Example 2
streams = [
[(9, 0.85)],
[(6, 0.90), (9, 0.75)],
[(9, 0.80), (11, 0.95)],
]
threshold = 0.75
max_gap = 3
Output:
[(9, 9)]
Walk-through:
- The three feeds produce active windows [(9, 9)], [(6, 9)], and [(9, 11)] respectively. All three windows cover timestamp 9 and no other common instant, producing [(9, 9)].
Constraints
0 <= len(streams) <= 1000 <= len(stream) <= 10^4for every feedstreaminstreams- Timestamps within each feed are strictly increasing integers satisfying
0 <= timestamp <= 10^9 0.0 <= intensity <= 1.00.0 <= threshold <= 1.00 <= max_gap <= 10^6
Step-by-step walkthrough
Understand the problem and split it into two clean phases
We have
ksensor feeds, each containing sorted(timestamp, intensity)observations. An observation counts as active whenintensity >= threshold, and consecutive active observations on the same feed merge into one continuous streak whenevert_curr - t_prev <= max_gap(splitting into separate windows whent_curr - t_prev > max_gap). Our goal is to find every closed interval[start, end]where allkfeeds are active simultaneously:threshold = 0.6, max_gap = 4 Feed 0 readings: (2, 0.75) (5, 0.20->skip) (6, 0.85) (13, 0.90) (16, 0.60) Feed 0 windows: [2 ================== 6] [13 ======== 16] Feed 1 readings: (4, 0.70) (8, 0.95) (15, 0.80) (22, 0.90) Feed 1 windows: [4 ================== 8] [15] [22] Shared by ALL: [4 ============= 6] [15]Notice two subtle details in the rules before writing code: - Gaps are measured between active readings only: If a camera records
(0, 0.9), (1, 0.1), (2, 0.9)withthreshold = 0.5andmax_gap = 2, the low reading(1, 0.1)is ignored, so the active readings at0and2have gap2 - 0 = 2 <= 2and form[0, 2]. - Single-instant intervals are valid: An isolated active reading attforms the closed interval[t, t], and two intervals touching only att(like[1, 5]and[5, 9]) share the valid single-point overlap[5, 5].Breaking the problem into two independent helpers makes each piece short and easy to verify: 1. Per camera (
active_intervals): convert one sorted stream of(timestamp, intensity)readings into a sorted list of disjoint closed intervals(start, end). 2. Across cameras (intersect_two+ fold): intersect those interval lists two at a time so only time ranges covered by every camera survive.Why discretizing timestamps fails, and how intervals solve it
A tempting beginner idea is to allocate a boolean array
is_active[t]for every integer timestampt, mark active seconds for each camera, and scan for runs where every camera hasTrue.Check the constraints to see why that fails on both memory and correctness: 1. Memory and speed blow-up:
timestampcan be as large as1,000,000,000(10^9), while each stream has at most10,000(10^4) readings. Allocating an array of length10^9consumes gigabytes of RAM and billions of steps even when a camera only fired twice (say att = 0andt = 10^9). 2. False merging onmax_gap = 0: Supposemax_gap = 0and two cameras both fire att = 5andt = 6. Because6 - 5 = 1 > 0, each camera has two separate point intervals[5, 5]and[6, 6]with an inactive gap in between (for example att = 5.5). An integer boolean array seesTrueat index5andTrueat index6and wrongly glues them into[5, 6]!Representing streaks directly as
(start_time, end_time)endpoint tuples avoids both traps: runtime and memory depend only on the number of readings (<= 10^4per stream), never on how huge the timestamps are.Phase 1: group one camera's active readings into intervals
Scan a single stream from left to right while tracking two variables: -
interval_start: the start timestamp of the currently open motion streak (Nonebefore the first active reading). -last_active_time: the timestamp of the most recent active reading.For each
(timestamp, intensity)pair: 1. Ifintensity < threshold, skip it (continue). 2. Ifinterval_start is None, open our very first interval attimestamp. 3. Else iftimestamp - last_active_time > max_gap, the silence was too long: close and append(interval_start, last_active_time), then start a fresh interval attimestamp. 4. Updatelast_active_time = timestamp.After the loop ends, if an interval is still open (
interval_start is not None), append(interval_start, last_active_time)so the final streak is not lost (and a lone active reading attcleanly becomes(t, t)).Trace on Feed 0: [(2, 0.75), (5, 0.20), (6, 0.85), (13, 0.90), (16, 0.60)], threshold=0.6, max_gap=4 (2, 0.75) >= 0.6 -> first active reading: interval_start=2, last_active_time=2 (5, 0.20) < 0.6 -> skip inactive reading (6, 0.85) >= 0.6 -> gap 6 - 2 = 4 <= 4: extend streak, last_active_time=6 (13, 0.90) >= 0.6 -> gap 13 - 6 = 7 > 4: append (2, 6); interval_start=13, last_active_time=13 (16, 0.60) >= 0.6 -> gap 16 - 13 = 3 <= 4: extend streak, last_active_time=16 end of loop -> flush open streak: append (13, 16) Result: [(2, 6), (13, 16)]from typing import List, Optional, Tuple def active_intervals( stream: List[Tuple[int, float]], threshold: float, max_gap: int, ) -> List[Tuple[int, int]]: """Disjoint closed intervals [start, end] during which one camera is active, in time order.""" # intervals: chronological list of disjoint closed (start_time, end_time) tuples. intervals: List[Tuple[int, int]] = [] interval_start: Optional[int] = None last_active_time: Optional[int] = None for timestamp, intensity in stream: # Ignore readings below threshold so gaps are measured between active readings only. if intensity < threshold: continue if interval_start is None: # First active reading opens a new interval. interval_start = timestamp elif timestamp - last_active_time > max_gap: # Strictly > max_gap splits: a gap equal to max_gap stays in the same interval. intervals.append((interval_start, last_active_time)) interval_start = timestamp last_active_time = timestamp # Flush the final open interval (an isolated reading at t becomes (t, t)). if interval_start is not None and last_active_time is not None: intervals.append((interval_start, last_active_time)) return intervalsPhase 2: intersect two interval lists with two pointers
Now suppose we have two sorted lists of disjoint closed intervals,
intervals_aandintervals_b. Place indexi = 0onintervals_aand indexj = 0onintervals_b.When do two closed intervals
[a_start, a_end]and[b_start, b_end]overlap? Both cameras are simultaneously active starting at the later start time (overlap_start = max(a_start, b_start)) and ending at the earlier end time (overlap_end = min(a_end, b_end)). Wheneveroverlap_start <= overlap_end, they share[overlap_start, overlap_end](use<=rather than<so a single-point touch likeoverlap_start == overlap_end == 5is kept!).Which pointer should advance next? Always advance whichever interval ends earlier:
intervals_a[i]: [2 ======= 6] intervals_b[j]: [4 =========== 8] [15 == 15] [22 == 22] |-- overlap --| Why advance i (since a_end = 6 < b_end = 8)? - Every future interval in intervals_b starts strictly AFTER 8 (e.g., 15), so [2, 6] can NEVER overlap anything else in intervals_b! - Meanwhile [4, 8] extends past 6, so it MIGHT still overlap intervals_a[i + 1]!Because every loop iteration increments either
iorj, intersecting two lists of lengthsAandBtakes at mostA + Bsteps.def intersect_two( intervals_a: List[Tuple[int, int]], intervals_b: List[Tuple[int, int]], ) -> List[Tuple[int, int]]: """Intersection of two sorted lists of disjoint closed intervals using two pointers.""" overlaps: List[Tuple[int, int]] = [] i = 0 j = 0 while i < len(intervals_a) and j < len(intervals_b): a_start, a_end = intervals_a[i] b_start, b_end = intervals_b[j] overlap_start = max(a_start, b_start) overlap_end = min(a_end, b_end) # Use <= because intervals are closed: overlap_start == overlap_end is a valid [t, t] overlap. if overlap_start <= overlap_end: overlaps.append((overlap_start, overlap_end)) # Advance whichever interval ends earlier: since both lists are sorted and disjoint, # the earlier-ending interval cannot overlap any later interval in the other list. if a_end < b_end: i += 1 else: j += 1 return overlapsPhase 3: fold across all cameras and verify output is already merged
Set intersection is associative (
A ∩ B ∩ C == (A ∩ B) ∩ C), so we initializesharedwith Camera 0's intervals and foldshared = intersect_two(shared, next_intervals)across Cameras1 .. k - 1—stopping early withbreakas soon assharedbecomes empty ([]). Ifstreamsitself is empty (0cameras), we return[].Let's double-check two important properties of this fold:
- Could two output intervals touch or overlap and need a separate merge pass? No! Within any single camera's interval list, consecutive intervals
(s1, e1)and(s2, e2)are separated by a gap strictly greater thanmax_gap >= 0(s2 - e1 >= max_gap + 1 >= 1, soe1 < s2). Wheneverintersect_twoemits(u1, v1)and then advances the earlier-ending interval (v1), the next candidate in that list starts strictly afterv1, guaranteeingv1 < u2strictly. Thus output intervals never overlap and never share an endpoint (like[10, 12]and[12, 14]). - Can
sharedblow up in size across100streams? No! Because consecutive intervals insharedare always more thanmax_gapapart, any single streak in Camerai - 1built fromractive readings (spaced<= max_gapapart) can cover at mostrintervals ofshared. Thus after folding Camerai - 1,len(shared)never exceedsA_{i - 1}(the number of active readings in Camerai - 1). Summing(len(shared) + len(next_intervals)) <= A_{i - 1} + A_iacross allk - 1merges totals at most2 * Nsteps—purely linear in the total number of readings!
def find_shared_motion_periods( streams: List[List[Tuple[int, float]]], threshold: float, max_gap: int, ) -> List[Tuple[int, int]]: """Maximal closed intervals during which every stream is active, in chronological order.""" if not streams: return [] # Start with camera 0's intervals and narrow down against each remaining camera. shared = active_intervals(streams[0], threshold, max_gap) for stream_idx in range(1, len(streams)): if not shared: # Once no shared time remains, later cameras cannot add any back. break next_intervals = active_intervals(streams[stream_idx], threshold, max_gap) shared = intersect_two(shared, next_intervals) return shared- Could two output intervals touch or overlap and need a separate merge pass? No! Within any single camera's interval list, consecutive intervals
Walk through Example 1 and Example 2 step by step
Trace
intersect_twopointer by pointer on Example 1 (threshold = 0.6,max_gap = 4):intervals_a (Feed 0): [(2, 6), (13, 16)] intervals_b (Feed 1): [(4, 8), (15, 15), (22, 22)] Iteration 1: i = 0 -> (2, 6), j = 0 -> (4, 8) overlap_start = max(2, 4) = 4 overlap_end = min(6, 8) = 6 4 <= 6 -> append (4, 6)! 6 < 8 -> advance i to 1 Iteration 2: i = 1 -> (13, 16), j = 0 -> (4, 8) overlap_start = max(13, 4) = 13 overlap_end = min(16, 8) = 8 13 <= 8 is False -> no overlap 16 < 8 is False -> advance j to 1 Iteration 3: i = 1 -> (13, 16), j = 1 -> (15, 15) overlap_start = max(13, 15) = 15 overlap_end = min(16, 15) = 15 15 <= 15 -> append (15, 15)! 16 < 15 is False -> advance j to 2 Iteration 4: i = 1 -> (13, 16), j = 2 -> (22, 22) overlap_start = max(13, 22) = 22 overlap_end = min(16, 22) = 16 22 <= 16 is False -> no overlap 16 < 22 is True -> advance i to 2 (loop ends because i == len(intervals_a)) Final output: [(4, 6), (15, 15)]And on Example 2 (
streams = [[(9, 0.85)], [(6, 0.90), (9, 0.75)], [(9, 0.80), (11, 0.95)]],threshold = 0.75,max_gap = 3): - Feed 0 produces[(9, 9)], Feed 1 produces[(6, 9)], and Feed 2 produces[(9, 11)]. - Intersecting[(9, 9)]with[(6, 9)]givesmax(9, 6) = 9 <= min(9, 9) = 9, keeping[(9, 9)]. - Intersecting[(9, 9)]with[(9, 11)]givesmax(9, 9) = 9 <= min(9, 11) = 9, returning[(9, 9)].Complete solution
from typing import List, Optional, Tuple def active_intervals( stream: List[Tuple[int, float]], threshold: float, max_gap: int, ) -> List[Tuple[int, int]]: """Disjoint closed intervals [start, end] during which one camera is active, in time order.""" # intervals: chronological list of disjoint closed (start_time, end_time) tuples. intervals: List[Tuple[int, int]] = [] interval_start: Optional[int] = None last_active_time: Optional[int] = None for timestamp, intensity in stream: # Ignore readings below threshold so gaps are measured between active readings only. if intensity < threshold: continue if interval_start is None: # First active reading opens a new interval. interval_start = timestamp elif timestamp - last_active_time > max_gap: # Strictly > max_gap splits: a gap equal to max_gap stays in the same interval. intervals.append((interval_start, last_active_time)) interval_start = timestamp last_active_time = timestamp # Flush the final open interval (an isolated reading at t becomes (t, t)). if interval_start is not None and last_active_time is not None: intervals.append((interval_start, last_active_time)) return intervals def intersect_two( intervals_a: List[Tuple[int, int]], intervals_b: List[Tuple[int, int]], ) -> List[Tuple[int, int]]: """Intersection of two sorted lists of disjoint closed intervals using two pointers.""" overlaps: List[Tuple[int, int]] = [] i = 0 j = 0 while i < len(intervals_a) and j < len(intervals_b): a_start, a_end = intervals_a[i] b_start, b_end = intervals_b[j] overlap_start = max(a_start, b_start) overlap_end = min(a_end, b_end) # Use <= because intervals are closed: overlap_start == overlap_end is a valid [t, t] overlap. if overlap_start <= overlap_end: overlaps.append((overlap_start, overlap_end)) # Advance whichever interval ends earlier: since both lists are sorted and disjoint, # the earlier-ending interval cannot overlap any later interval in the other list. if a_end < b_end: i += 1 else: j += 1 return overlaps def find_shared_motion_periods( streams: List[List[Tuple[int, float]]], threshold: float, max_gap: int, ) -> List[Tuple[int, int]]: """Maximal closed intervals during which every stream is active, in chronological order.""" if not streams: return [] # Start with camera 0's intervals and narrow down against each remaining camera. shared = active_intervals(streams[0], threshold, max_gap) for stream_idx in range(1, len(streams)): if not shared: # Once no shared time remains, later cameras cannot add any back. break next_intervals = active_intervals(streams[stream_idx], threshold, max_gap) shared = intersect_two(shared, next_intervals) return shared✅ Submit now — all tests should pass.
Intuition & how it works
Think of each camera's high-intensity readings like footprints in the snow: whenever the next footprint appears within max_gap seconds of the previous one, you connect them into one continuous motion streak; when silence lasts strictly longer than max_gap, that streak ends and a new one begins later. Each streak is a closed interval [start, end] (a time range that includes both its starting and ending timestamps). Once every camera has its own sorted list of streaks, finding shared motion is like laying one translucent highlighter strip per camera onto a timeline and reading off the segments where every single color overlaps.
A naive approach—allocating a boolean array for every timestamp from 0 up to 10^9—wastes gigabytes of memory and billions of steps even when a camera only recorded 3 readings, and wrongly glues adjacent point intervals like [5, 5] and [6, 6] together when max_gap = 0. Comparing every interval of one stream against every interval of the next is also needlessly quadratic (O(R^2)). Instead, a two-pointer scan (marching one index through each sorted interval list and always discarding whichever interval finishes first) computes each pairwise intersection in a single linear pass.
Walk through a tiny concrete trace on Example 1 (threshold = 0.6, max_gap = 4):
1. Build Feed 0 intervals: Active timestamps are 2, 6, 13, 16 (5 has intensity 0.20 < 0.6). Because 6 - 2 = 4 <= 4 joins, 13 - 6 = 7 > 4 splits, and 16 - 13 = 3 <= 4 joins, Feed 0 yields [(2, 6), (13, 16)].
2. Build Feed 1 intervals: Active timestamps are 4, 8, 15, 22. Gap 8 - 4 = 4 <= 4 joins while gaps 7 and 7 split, so Feed 1 yields [(4, 8), (15, 15), (22, 22)].
3. Two-pointer intersection: Compare (2, 6) with (4, 8): max(2, 4) = 4 <= min(6, 8) = 6 emits (4, 6), and 6 < 8 advances Feed 0 to (13, 16). Next, (13, 16) against (4, 8) has 13 > 8 (advance Feed 1), (13, 16) against (15, 15) emits (15, 15) (advance Feed 1), and (13, 16) against (22, 22) has 22 > 16 (advance Feed 0 and finish), returning [(4, 6), (15, 15)].
Complexity
- Time:
O(N)(more preciselyO(N + 1)with early exit on emptyshared), whereNis the total number of sensor readings across all streams. Scanning each visited stream inactive_intervalstouches each reading at most once (O(N)total). In thei-th pairwise mergeintersect_two(shared, next_intervals), consecutive intervals insharedare separated by strictly more thanmax_gap, solen(shared)never exceedsA_{i - 1}(the number of active readings in streami - 1). Summinglen(shared) + len(next_intervals) <= A_{i - 1} + A_ioveri = 1 .. k - 1gives at most2 * Npointer advances across all intersections combined (and if any stream produces[],if not shared: breakstops on the very next iteration without even touching the remaining streams). - Space:
O(R), whereRis the maximum number of readings in a single stream (R <= 10^4). At any moment we hold only the runningsharedlist and one camera'snext_intervalslist, each containing at mostRtuples, without copying or mutating the inputstreams.
Edge cases
- No cameras (
streams == []): Returns[]immediately rather than raisingIndexErroronstreams[0]. - Single camera (
len(streams) == 1): The loop overrange(1, len(streams))runs zero times and returns that single camera's active intervals directly. - Empty stream or camera with zero active readings: Produces
[], causingsharedto become[]andbreakout of the remaining streams immediately. - Exact boundary ties (
intensity == thresholdandgap == max_gap):intensity >= thresholdcounts as active, andtimestamp - last_active_time == max_gapstays in the same interval (>splits,<=joins). - Single-point overlap (
[1, 5]and[5, 9], or two isolated readings att = 5):overlap_start == overlap_end == 5satisfiesoverlap_start <= overlap_end, producing the valid closed point interval(5, 5). max_gap = 0with consecutive integer timestamps (t = 5andt = 6): Each reading forms its own point interval(5, 5)and(6, 6); because6 - 5 = 1 > 0, the cameras were not continuously active between5and6, so they stay two separate intervals[(5, 5), (6, 6)]rather than merging into(5, 6).
Common mistakes
- Checking
overlap_start < overlap_endinstead ofoverlap_start <= overlap_end: Using<drops valid single-instant overlaps like(15, 15)in Example 1 and(9, 9)in Example 2. - Advancing the interval that ends later instead of earlier: If
(4, 8)is discarded before(2, 6), you miss later intervals inside Feed 0 (such as(7, 8)) that also overlap(4, 8). - Forgetting to flush
(interval_start, last_active_time)after theforloop: Without the post-loopif interval_start is not None:check, the final active streak of every camera is silently lost! - Measuring gaps against inactive readings: Checking
timestamp - prev_timestampbefore filteringintensity >= thresholdlets an inactive reading att = 1break or falsely bridge active readings att = 0andt = 2. - Merging integer-adjacent point intervals like
(5, 5)and(6, 6): Touching closed intervals share an endpoint ([10, 12]and[12, 14]share12and merge into[10, 14]), whereas(5, 5)and(6, 6)have an open gap(5, 6)between them where motion exceededmax_gap = 0. - Mutating input lists in place: Calling
.pop()or.sort()on caller-owned lists violates the problem contract; iterating read-only and returning fresh lists leaves inputs untouched.
Alternative approaches
- Event sweep-line (
O(T log T)forTtotal intervals): Convert every camera interval(start, end)into two events—(start, 0)for open and(end, 1)for close, sorting opens before closes at equal timestamps—sort all2Tevents, and emit intervals whenever the active-camera counter equalsk. A sweep-line algorithm processes sorted start/end events along a timeline using a running counter; it addslog Tsorting overhead here because the streams are already sorted, but generalizes effortlessly to "at leastMofNcameras." k-way min-heap merge (O(T log k)): Push the first event of each camera's interval list into a min-heap (a priority queue that pops the earliest event inO(log k)time) to run the sweep-line in chronological order without sorting all2Tevents up front.
Follow-up questions
- What changes are needed when sensor events arrive out of chronological order or device clocks drift relative to one another? For out-of-order observations in batch mode, sort a copy of each feed by
timestampbefore callingactive_intervals; in live streaming mode, buffer incoming events per feed in a min-heap up to a watermark (a moving timestamp cutoff behind which we assume delayed packets have arrived) before finalizing streaks. For clock drift (devices whose internal clocks disagree by up todmilliseconds), synchronize sensors via NTP/PTP or subtract each device's estimated clock offset; if bounded residual skewdremains, pad every extracted window symmetrically to[start - d/2, end + d/2]before intersecting so simultaneous activity recorded up todapart still overlaps. - How could you convert this batch procedure into a real-time processor over unbounded feeds while keeping memory usage capped? Maintain
O(1)streak-builder state per feed (interval_startandlast_active_time), emitting a closed interval(interval_start, last_active_time)into that feed's bounded FIFO queue as soon as an active observation arrives more thanmax_gaplater (or a heartbeat advances pastlast_active_time + max_gap, adding an unavoidable output latency ofmax_gap). Track the global safe frontierW = min(finalized_up_to[c] for all feeds c), advance the multi-feed intersection up toW, and immediately evict any queued interval withend < W. Memory stays bounded byO(k + intervals active within the lag window)regardless of how many months the feeds run. - How would your design change if an output window only required at least
Mof theNfeeds to be active simultaneously? Pairwise intersection (intersect_two) no longer works whenM < N, because different subsets ofMfeeds can carry the threshold from one moment to the next (for instance, Feeds 1 & 2 on[0, 5]and Feeds 2 & 3 on[5, 10]keep>= 2feeds active across all of[0, 10]). Instead, extractactive_intervalsper feed as before and run a sweep-line over(start, 0)(open) and(end, 1)(close) events sorted with opens (0) before closes (1) at equal timestamps: recordwindow_start = timewhenactive_countrises fromM - 1toM, and emit(window_start, time)whenactive_countdrops fromMtoM - 1inO(T log T)time. Sorting opens before closes at timestamp5keepsactive_count >= 2acrosst = 5, automatically merging[0, 5]and[5, 10]into[(0, 10)]with no extra merge pass.
Follow-up questions
- What changes are needed when sensor events arrive out of chronological order or device clocks drift relative to one another?
- How could you convert this batch procedure into a real-time processor over unbounded feeds while keeping memory usage capped?
- How would your design change if an output window only required at least `M` of the `N` feeds to be active simultaneously?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array