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

  1. Per-feed active windows (active_intervals):

    • An observation (timestamp, intensity) counts as active whenever intensity >= threshold. Observations strictly below threshold are ignored completely (they neither start windows nor affect time differences between active observations).
    • Two consecutive active observations on the same feed at t_prev and t_curr stay within the same continuous closed window [start, end] when t_curr - t_prev <= max_gap. Whenever t_curr - t_prev > max_gap, the current window ends at t_prev and a fresh window opens at t_curr.
    • A single active observation with no neighboring active observation within max_gap forms a zero-length closed window (t, t).
    • Return the resulting disjoint closed (start, end) tuples in ascending chronological order.
  2. All-feed shared windows (find_shared_motion_periods):

    • Return every maximal closed interval (start, end) during which every feed in streams is active simultaneously, sorted in chronological order.
    • Instantaneous overlaps of the form (t, t) are valid whenever every feed covers timestamp t.
    • 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) when max_gap == 0, remain distinct).
    • If streams is empty (0 feeds), return [].
    • Leave streams and all inner lists unmodified.

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) <= 100
  • 0 <= len(stream) <= 10^4 for every feed stream in streams
  • Timestamps within each feed are strictly increasing integers satisfying 0 <= timestamp <= 10^9
  • 0.0 <= intensity <= 1.0
  • 0.0 <= threshold <= 1.0
  • 0 <= max_gap <= 10^6

Step-by-step walkthrough

  1. Understand the problem and split it into two clean phases

    We have k sensor feeds, each containing sorted (timestamp, intensity) observations. An observation counts as active when intensity >= threshold, and consecutive active observations on the same feed merge into one continuous streak whenever t_curr - t_prev <= max_gap (splitting into separate windows when t_curr - t_prev > max_gap). Our goal is to find every closed interval [start, end] where all k feeds 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) with threshold = 0.5 and max_gap = 2, the low reading (1, 0.1) is ignored, so the active readings at 0 and 2 have gap 2 - 0 = 2 <= 2 and form [0, 2]. - Single-instant intervals are valid: An isolated active reading at t forms the closed interval [t, t], and two intervals touching only at t (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.

  2. 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 timestamp t, mark active seconds for each camera, and scan for runs where every camera has True.

    Check the constraints to see why that fails on both memory and correctness: 1. Memory and speed blow-up: timestamp can be as large as 1,000,000,000 (10^9), while each stream has at most 10,000 (10^4) readings. Allocating an array of length 10^9 consumes gigabytes of RAM and billions of steps even when a camera only fired twice (say at t = 0 and t = 10^9). 2. False merging on max_gap = 0: Suppose max_gap = 0 and two cameras both fire at t = 5 and t = 6. Because 6 - 5 = 1 > 0, each camera has two separate point intervals [5, 5] and [6, 6] with an inactive gap in between (for example at t = 5.5). An integer boolean array sees True at index 5 and True at index 6 and 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^4 per stream), never on how huge the timestamps are.

  3. 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 (None before the first active reading). - last_active_time: the timestamp of the most recent active reading.

    For each (timestamp, intensity) pair: 1. If intensity < threshold, skip it (continue). 2. If interval_start is None, open our very first interval at timestamp. 3. Else if timestamp - last_active_time > max_gap, the silence was too long: close and append (interval_start, last_active_time), then start a fresh interval at timestamp. 4. Update last_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 at t cleanly 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 intervals
    
  4. Phase 2: intersect two interval lists with two pointers

    Now suppose we have two sorted lists of disjoint closed intervals, intervals_a and intervals_b. Place index i = 0 on intervals_a and index j = 0 on intervals_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)). Whenever overlap_start <= overlap_end, they share [overlap_start, overlap_end] (use <= rather than < so a single-point touch like overlap_start == overlap_end == 5 is 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 i or j, intersecting two lists of lengths A and B takes at most A + B steps.

    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
    
  5. Phase 3: fold across all cameras and verify output is already merged

    Set intersection is associative (A ∩ B ∩ C == (A ∩ B) ∩ C), so we initialize shared with Camera 0's intervals and fold shared = intersect_two(shared, next_intervals) across Cameras 1 .. k - 1—stopping early with break as soon as shared becomes empty ([]). If streams itself is empty (0 cameras), we return [].

    Let's double-check two important properties of this fold:

    1. 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 than max_gap >= 0 (s2 - e1 >= max_gap + 1 >= 1, so e1 < s2). Whenever intersect_two emits (u1, v1) and then advances the earlier-ending interval (v1), the next candidate in that list starts strictly after v1, guaranteeing v1 < u2 strictly. Thus output intervals never overlap and never share an endpoint (like [10, 12] and [12, 14]).
    2. Can shared blow up in size across 100 streams? No! Because consecutive intervals in shared are always more than max_gap apart, any single streak in Camera i - 1 built from r active readings (spaced <= max_gap apart) can cover at most r intervals of shared. Thus after folding Camera i - 1, len(shared) never exceeds A_{i - 1} (the number of active readings in Camera i - 1). Summing (len(shared) + len(next_intervals)) <= A_{i - 1} + A_i across all k - 1 merges totals at most 2 * N steps—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
    
  6. Walk through Example 1 and Example 2 step by step

    Trace intersect_two pointer 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)] gives max(9, 6) = 9 <= min(9, 9) = 9, keeping [(9, 9)]. - Intersecting [(9, 9)] with [(9, 11)] gives max(9, 9) = 9 <= min(9, 11) = 9, returning [(9, 9)].

  7. 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 precisely O(N + 1) with early exit on empty shared), where N is the total number of sensor readings across all streams. Scanning each visited stream in active_intervals touches each reading at most once (O(N) total). In the i-th pairwise merge intersect_two(shared, next_intervals), consecutive intervals in shared are separated by strictly more than max_gap, so len(shared) never exceeds A_{i - 1} (the number of active readings in stream i - 1). Summing len(shared) + len(next_intervals) <= A_{i - 1} + A_i over i = 1 .. k - 1 gives at most 2 * N pointer advances across all intersections combined (and if any stream produces [], if not shared: break stops on the very next iteration without even touching the remaining streams).
  • Space: O(R), where R is the maximum number of readings in a single stream (R <= 10^4). At any moment we hold only the running shared list and one camera's next_intervals list, each containing at most R tuples, without copying or mutating the input streams.

Edge cases

  • No cameras (streams == []): Returns [] immediately rather than raising IndexError on streams[0].
  • Single camera (len(streams) == 1): The loop over range(1, len(streams)) runs zero times and returns that single camera's active intervals directly.
  • Empty stream or camera with zero active readings: Produces [], causing shared to become [] and break out of the remaining streams immediately.
  • Exact boundary ties (intensity == threshold and gap == max_gap): intensity >= threshold counts as active, and timestamp - last_active_time == max_gap stays in the same interval (> splits, <= joins).
  • Single-point overlap ([1, 5] and [5, 9], or two isolated readings at t = 5): overlap_start == overlap_end == 5 satisfies overlap_start <= overlap_end, producing the valid closed point interval (5, 5).
  • max_gap = 0 with consecutive integer timestamps (t = 5 and t = 6): Each reading forms its own point interval (5, 5) and (6, 6); because 6 - 5 = 1 > 0, the cameras were not continuously active between 5 and 6, so they stay two separate intervals [(5, 5), (6, 6)] rather than merging into (5, 6).

Common mistakes

  • Checking overlap_start < overlap_end instead of overlap_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 the for loop: Without the post-loop if interval_start is not None: check, the final active streak of every camera is silently lost!
  • Measuring gaps against inactive readings: Checking timestamp - prev_timestamp before filtering intensity >= threshold lets an inactive reading at t = 1 break or falsely bridge active readings at t = 0 and t = 2.
  • Merging integer-adjacent point intervals like (5, 5) and (6, 6): Touching closed intervals share an endpoint ([10, 12] and [12, 14] share 12 and merge into [10, 14]), whereas (5, 5) and (6, 6) have an open gap (5, 6) between them where motion exceeded max_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) for T total 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 all 2T events, and emit intervals whenever the active-camera counter equals k. A sweep-line algorithm processes sorted start/end events along a timeline using a running counter; it adds log T sorting overhead here because the streams are already sorted, but generalizes effortlessly to "at least M of N cameras."
  • 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 in O(log k) time) to run the sweep-line in chronological order without sorting all 2T events 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 timestamp before calling active_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 to d milliseconds), synchronize sensors via NTP/PTP or subtract each device's estimated clock offset; if bounded residual skew d remains, pad every extracted window symmetrically to [start - d/2, end + d/2] before intersecting so simultaneous activity recorded up to d apart 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_start and last_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 than max_gap later (or a heartbeat advances past last_active_time + max_gap, adding an unavoidable output latency of max_gap). Track the global safe frontier W = min(finalized_up_to[c] for all feeds c), advance the multi-feed intersection up to W, and immediately evict any queued interval with end < W. Memory stays bounded by O(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 M of the N feeds to be active simultaneously? Pairwise intersection (intersect_two) no longer works when M < N, because different subsets of M feeds 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 >= 2 feeds active across all of [0, 10]). Instead, extract active_intervals per 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: record window_start = time when active_count rises from M - 1 to M, and emit (window_start, time) when active_count drops from M to M - 1 in O(T log T) time. Sorting opens before closes at timestamp 5 keeps active_count >= 2 across t = 5, automatically merging [0, 5] and [5, 10] into [(0, 10)] with no extra merge pass.

Follow-up questions

Similar questions

More Serval interview questions

All 1 Serval questions →