Centered Rolling Means and Grouped Interval Merging
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Implement two independent tabular data-processing routines in pure Python:
1. Centered Sliding-Window Mean (centered_window_average)
You are given rows, a list of (row_id, value) pairs already ordered strictly ascending by integer row_id, together with an integer radius k >= 0.
For each index i (0 <= i < len(rows)):
- If at least k rows appear before index i and at least k rows appear after index i, compute window_avg as the arithmetic mean of the 2 * k + 1 contiguous values value[i - k], ..., value[i], ..., value[i + k].
- Otherwise (on the first k positions and the final k positions), assign window_avg = -1.0.
Return a list of (row_id, value, window_avg) tuples in the same order as rows. Raise ValueError when k < 0.
2. Grouped Interval Coalescing (merge_intervals)
You are given rows, a list of tuples (*group_key, start, end), and an integer num_keys >= 0 telling how many leading elements form group_key:
- num_keys = 0: (start, end) — every interval belongs to one shared group.
- num_keys = 1: (unit_id, start, end) — intervals merge separately per unit_id.
- num_keys = 2: (unit_id, signal_kind, start, end) — intervals merge separately per (unit_id, signal_kind) pair (and similarly for any num_keys >= 0).
Here start and end are mutually comparable endpoints (such as integers or timezone-aligned datetime objects) satisfying start <= end. Within each group, two intervals coalesce whenever they overlap or touch at an endpoint (next_start <= current_end).
Return one tuple (*group_key, merged_start, merged_end) per coalesced interval, sorted ascending by group_key and then by merged_start. Raise ValueError if num_keys < 0, if any row's length differs from num_keys + 2, or if any row has start > end.
Examples
Example 1
Input:
rows = [(10, 3.0), (20, 6.0), (30, 12.0), (40, 0.0), (50, 9.0)]
k = 1
Output:
[(10, 3.0, -1.0), (20, 6.0, 7.0), (30, 12.0, 6.0), (40, 0.0, 7.0), (50, 9.0, -1.0)]
Walk-through: With k = 1, a full window spans 3 consecutive rows. Index 0 (row_id = 10) lacks a predecessor and index 4 (row_id = 50) lacks a successor, so both receive -1.0. The interior rows average (3 + 6 + 12) / 3 = 7.0, (6 + 12 + 0) / 3 = 6.0, and (12 + 0 + 9) / 3 = 7.0.
Example 2
Input:
rows = [("car_b", 50, 58), ("car_a", 5, 15), ("car_a", 25, 35), ("car_a", 15, 20), ("car_b", 52, 55)]
num_keys = 1
Output:
[("car_a", 5, 20), ("car_a", 25, 35), ("car_b", 50, 58)]
Walk-through: For "car_a", [5, 15] and [15, 20] touch at 15 (15 <= 15) and coalesce into [5, 20], while [25, 35] starts strictly after 20 and remains separate. For "car_b", [52, 55] sits inside [50, 58], leaving [50, 58]. Results are ordered by unit ID ("car_a" before "car_b") and then start time.
Example 3
Input:
rows = [
("car_a", "steer", 10, 18),
("car_a", "lidar", 14, 22),
("car_a", "steer", 18, 24),
("car_b", "steer", 12, 20),
]
num_keys = 2
Output:
[
("car_a", "lidar", 14, 22),
("car_a", "steer", 10, 24),
("car_b", "steer", 12, 20),
]
Walk-through: Grouping uses both (unit_id, signal_kind). For ("car_a", "steer"), [10, 18] and [18, 24] touch at 18 and merge into [10, 24]; ("car_a", "lidar") and ("car_b", "steer") never merge across distinct keys even though their time ranges overlap.
Constraints
0 <= len(rows) <= 10^5for both functions.- In
centered_window_average:k >= 0(raiseValueErrorifk < 0);rowsis pre-sorted strictly ascending byrow_id;valueis a finiteintorfloat; target complexity isO(n)time (independent ofk) andO(n)space. - In
merge_intervals:num_keys >= 0,len(row) == num_keys + 2, andstart <= endfor every row (raiseValueErroron any violation); group keys and endpoints are mutually comparable within their positions; target complexity isO(n log n)time andO(n)space.
Step-by-step walkthrough
Understand both tasks and their input/output shapes
We have two independent data-processing tasks. In our Python implementation, each table row is represented as a tuple in column order so the code runs anywhere with the standard library alone (the
pandasDataFrame equivalents follow the exact same logic and are shown in the explanation).Task 1: Centered sliding-window average (
centered_window_average). Each input row is(row_id, value), already sorted byrow_idascending. Givenk >= 0, rowilookskrows backward andkrows forward — a symmetric window of2 * k + 1values:Index i: 0 1 2 3 4 (num_rows = 5, k = 1, window_width = 3) Values: [3.0, 6.0, 12.0, 0.0, 9.0] |______|______| window for i = 2 -> (6.0 + 12.0 + 0.0) / 3 = 6.0 Row i = 0 has 0 rows on its left (needs 1) -> window_avg = -1.0 Row i = 4 has 0 rows on its right (needs 1) -> window_avg = -1.0A row gets a real average only when both
i - k >= 0andi + k < num_rows. Otherwisewindow_avgis-1.0.Task 2: Grouped interval merging (
merge_intervals). Each input row is(*group_key, start, end)wherenum_keys(0,1, or2) tells us how many leading columns form the group key:num_keys = 0: (start, end) -> whole table is one group () num_keys = 1: (unit_id, start, end) -> group per unit_id num_keys = 2: (unit_id, signal_kind, start, end) -> group per (unit_id, signal_kind)Within each group, two intervals merge whenever they overlap or touch (
next.start <= current.end), and the output is sorted by group key, thenmerged_start.Task 1: Turn O(n * k) window sums into O(1) lookups with prefix sums
A direct loop slices
values[i - k : i + k + 1]and sums all2 * k + 1numbers for every row. Withn = 1,000,000rows andk = 1,000, each window adds2,001numbers, costing roughly2 * 10^9additions (O(n * k)time).Notice that neighboring windows overlap almost completely: moving from row
ito rowi + 1drops one value on the left and adds one value on the right. A prefix sum array — a precomputed list where entryjstores the sum of the firstjvalues (value[0] + ... + value[j - 1], starting withprefix_sums[0] = 0.0) — lets us compute any contiguous slice sum in a single subtraction:Index: 0 1 2 3 4 5 values: 3.0 6.0 12.0 0.0 9.0 prefix_sums: [0.0, 3.0, 9.0, 21.0, 21.0, 30.0] Sum of values[1 .. 3] (6.0 + 12.0 + 0.0 = 18.0): prefix_sums[3 + 1] - prefix_sums[1] = prefix_sums[4] - prefix_sums[1] = 21.0 - 3.0 = 18.0Why is the right index
right_index + 1? Becauseprefix_sums[m]adds values up to indexm - 1. To includevalue[right_index], we readprefix_sums[right_index + 1], and to keepvalue[left_index]inside the window, we subtract only the elements strictly before it (prefix_sums[left_index]).Code Task 1: centered_window_average
First reject negative
kwithValueError. Buildprefix_sumsin one pass, then sweeprowsonce, dividingwindow_sumbywindow_width = 2 * k + 1whenever both window endpoints stay in bounds:def centered_window_average(rows: List[Tuple[int, float]], k: int) -> List[Tuple[int, float, float]]: if k < 0: raise ValueError("k must be >= 0") num_rows = len(rows) # Phase 1: Build prefix sums so any window sum takes O(1) subtraction instead of O(k) addition. # prefix_sums: list of length (num_rows + 1) where prefix_sums[j] = sum(value[0 .. j-1]). # Mini-shape for values [2.0, 4.0, 9.0]: prefix_sums = [0.0, 2.0, 6.0, 15.0]. prefix_sums = [0.0] for _row_id, value in rows: prefix_sums.append(prefix_sums[-1] + value) # Phase 2: Sweep each row i and check whether [i - k, i + k] stays inside [0, num_rows - 1]. window_width = 2 * k + 1 result: List[Tuple[int, float, float]] = [] for i, (row_id, value) in enumerate(rows): left_index = i - k right_index = i + k has_full_window = left_index >= 0 and right_index < num_rows if has_full_window: # prefix_sums[right_index + 1] includes value[right_index]; subtracting # prefix_sums[left_index] removes everything strictly before left_index. window_sum = prefix_sums[right_index + 1] - prefix_sums[left_index] window_avg = window_sum / window_width else: window_avg = -1.0 result.append((row_id, value, window_avg)) return resultNote that
window_widthis always at least1(whenk = 0,window_width = 1,left_index = right_index = i, and every row returns its ownvalue), so we never divide by zero.Task 2: Sort by group and start time so one sweep merges everything
Checking every pair of intervals for overlap takes
O(n^2)time, and merging two intervals can create a wider interval that now touches a third one. Sorting solves both problems at once.When we unpack each row into
(group_key, start, end)and sort all tuples: 1. All rows with the samegroup_keysit together in one contiguous run. 2. Inside each group, intervals appear in non-decreasingstartorder (start_1 <= start_2 <= ...).Because the next interval in the same group is guaranteed to have
start >= current_start, there are only two possibilities relative to the currently open interval[current_start, current_end]:Case A: start <= current_end (overlaps or touches -> extend current_end) Open: [1 ================ 10] Next 1: [2 == 3] -> nested! max(10, 3) keeps current_end = 10 Next 2: [9 ======== 15] -> 9 <= 10! max(10, 15) extends current_end = 15 Case B: start > current_end (strict gap -> emit [1, 15], start new interval [16, 20]) Next 3: [16 === 20] (16 > 15 -> gap!)Two details here prevent classic bugs: - Use
<=, not<:[1, 3]and[3, 5]touch at3, and3 <= 3merges them into[1, 5]. - Usemax(current_end, end), notend: In Case A above,[2, 3]lies completely inside[1, 10]. Overwritingcurrent_endwith3would shrink the interval and cause[9, 15]to be missed.Code Task 2: merge_intervals
We validate
num_keys >= 0, check each row's length andstart <= end, sort once, sweep while maintaining(current_key, current_start, current_end), and flush the final open interval after the loop:def merge_intervals(rows: List[Tuple[Any, ...]], num_keys: int) -> List[Tuple[Any, ...]]: if num_keys < 0: raise ValueError("num_keys must be >= 0") # Phase 1: Validate every row and unpack into (group_key, start, end) before sorting. # parsed_rows: list of (group_key_tuple, start, end), e.g. (("v1",), 0, 10). parsed_rows: List[Tuple[Tuple[Any, ...], Any, Any]] = [] for row in rows: if len(row) != num_keys + 2: raise ValueError(f"expected {num_keys + 2} elements per row, got {row!r}") group_key = tuple(row[:num_keys]) start = row[num_keys] end = row[num_keys + 1] if start > end: raise ValueError(f"interval has start > end: {row!r}") parsed_rows.append((group_key, start, end)) # Sorting tuples places identical group_keys into one contiguous block ordered by start, then end. ordered_rows = sorted(parsed_rows) # Phase 2: Sweep left to right, keeping one active interval [current_start, current_end] open. # merged: list of (*group_key, merged_start, merged_end) tuples emitted in sorted order. merged: List[Tuple[Any, ...]] = [] current_key = None current_start = None current_end = None for group_key, start, end in ordered_rows: # Use <= (not <) because touching intervals like [1, 3] and [3, 5] must merge into [1, 5]. if current_key is not None and group_key == current_key and start <= current_end: # Use max() because a nested interval like [2, 3] inside [1, 10] ends earlier than 10. current_end = max(current_end, end) else: if current_key is not None: merged.append(current_key + (current_start, current_end)) current_key = group_key current_start = start current_end = end # Phase 3: Flush the last open interval once the sweep finishes. if current_key is not None: merged.append(current_key + (current_start, current_end)) return mergedNotice why
current_key = Noneworks cleanly even whennum_keys = 0: fornum_keys = 0,group_keyis the empty tuple(), which is notNone, so all rows share the single key()and merge together.Trace both algorithms step by step on concrete examples
Trace 1:
centered_window_averagewithk = 1on[(10, 3.0), (20, 6.0), (30, 12.0), (40, 0.0), (50, 9.0)].prefix_sums = [0.0, 3.0, 9.0, 21.0, 21.0, 30.0],num_rows = 5,window_width = 3:i row_id [left, right] in bounds? window_sum window_avg 0 10 [-1, 1] no - -1.0 1 20 [ 0, 2] yes prefix_sums[3] - prefix_sums[0] = 21.0 7.0 2 30 [ 1, 3] yes prefix_sums[4] - prefix_sums[1] = 18.0 6.0 3 40 [ 2, 4] yes prefix_sums[5] - prefix_sums[2] = 21.0 7.0 4 50 [ 3, 5] no - -1.0Trace 2:
merge_intervalswithnum_keys = 1on Example 2.Sorted input Active open interval Why / Action (("car_a",), 5, 15) ("car_a", 5, 15) First row: open ("car_a", 5, 15) (("car_a",), 15, 20) ("car_a", 5, 20) Same key & 15 <= 15 (touches): extend end to max(15, 20) = 20 (("car_a",), 25, 35) ("car_a", 25, 35) Same key & 25 > 20 (gap): emit ("car_a", 5, 20), open ("car_a", 25, 35) (("car_b",), 50, 58) ("car_b", 50, 58) Key changed ("car_b" != "car_a"): emit ("car_a", 25, 35), open ("car_b", 50, 58) (("car_b",), 52, 55) ("car_b", 50, 58) Same key & 52 <= 58 (nested): end stays max(58, 55) = 58 <end of loop> - Flush final open interval: emit ("car_b", 50, 58)Output:
[("car_a", 5, 20), ("car_a", 25, 35), ("car_b", 50, 58)].Complete solution
from typing import Any, List, Tuple def centered_window_average(rows: List[Tuple[int, float]], k: int) -> List[Tuple[int, float, float]]: """Task 1: centered sliding-window average. rows[i] = (row_id, value), already sorted by row_id ascending. k >= 0. Return one tuple (row_id, value, window_avg) per input row, in the same order, where window_avg = mean(value[i-k], ..., value[i+k]) when row i has at least k rows before it and k rows after it, and -1.0 otherwise. Raise ValueError if k < 0. """ if k < 0: raise ValueError("k must be >= 0") num_rows = len(rows) # Phase 1: Build prefix sums so any window sum takes O(1) subtraction instead of O(k) addition. # prefix_sums: list of length (num_rows + 1) where prefix_sums[j] = sum(value[0 .. j-1]). # Mini-shape for values [2.0, 4.0, 9.0]: prefix_sums = [0.0, 2.0, 6.0, 15.0]. prefix_sums = [0.0] for _row_id, value in rows: prefix_sums.append(prefix_sums[-1] + value) # Phase 2: Sweep each row i and check whether [i - k, i + k] stays inside [0, num_rows - 1]. window_width = 2 * k + 1 result: List[Tuple[int, float, float]] = [] for i, (row_id, value) in enumerate(rows): left_index = i - k right_index = i + k has_full_window = left_index >= 0 and right_index < num_rows if has_full_window: # prefix_sums[right_index + 1] includes value[right_index]; subtracting # prefix_sums[left_index] removes everything strictly before left_index. window_sum = prefix_sums[right_index + 1] - prefix_sums[left_index] window_avg = window_sum / window_width else: window_avg = -1.0 result.append((row_id, value, window_avg)) return result def merge_intervals(rows: List[Tuple[Any, ...]], num_keys: int) -> List[Tuple[Any, ...]]: """Task 2: merge overlapping or touching intervals within each group. rows[i] = (*group_key, start, end) with num_keys group-key columns (0, 1 or 2), e.g. num_keys=0: (start, end) the whole table is one group num_keys=1: (vehicle_id, start_ts, end_ts) num_keys=2: (vehicle_id, event_type, start_ts, end_ts) start and end are comparable values (ints or datetimes) with start <= end. Within a group, a later interval joins the current one when next.start <= current.end. Return one tuple (*group_key, merged_start, merged_end) per merged interval, sorted by the group key, then merged_start. Raise ValueError if a row has start > end. """ if num_keys < 0: raise ValueError("num_keys must be >= 0") # Phase 1: Validate every row and unpack into (group_key, start, end) before sorting. # parsed_rows: list of (group_key_tuple, start, end), e.g. (("v1",), 0, 10). parsed_rows: List[Tuple[Tuple[Any, ...], Any, Any]] = [] for row in rows: if len(row) != num_keys + 2: raise ValueError(f"expected {num_keys + 2} elements per row, got {row!r}") group_key = tuple(row[:num_keys]) start = row[num_keys] end = row[num_keys + 1] if start > end: raise ValueError(f"interval has start > end: {row!r}") parsed_rows.append((group_key, start, end)) # Sorting tuples places identical group_keys into one contiguous block ordered by start, then end. ordered_rows = sorted(parsed_rows) # Phase 2: Sweep left to right, keeping one active interval [current_start, current_end] open. # merged: list of (*group_key, merged_start, merged_end) tuples emitted in sorted order. merged: List[Tuple[Any, ...]] = [] current_key = None current_start = None current_end = None for group_key, start, end in ordered_rows: # Use <= (not <) because touching intervals like [1, 3] and [3, 5] must merge into [1, 5]. if current_key is not None and group_key == current_key and start <= current_end: # Use max() because a nested interval like [2, 3] inside [1, 10] ends earlier than 10. current_end = max(current_end, end) else: if current_key is not None: merged.append(current_key + (current_start, current_end)) current_key = group_key current_start = start current_end = end # Phase 3: Flush the last open interval once the sweep finishes. if current_key is not None: merged.append(current_key + (current_start, current_end)) return merged✅ Submit now — all tests should pass.
Intuition & how it works
Think of the two tasks as two classic timeline tricks: reading a trip odometer for sliding windows, and laying overlapping strips of tape from left to right for interval merging.
1. In Task 1, if you record cumulative totals along a road (a prefix sum, where entry j holds the sum of the first j numbers), the sum of any stretch from i - k to i + k is just "odometer at the end minus odometer at the start," divided by 2 * k + 1.
2. In Task 2, if you first sort every telemetry interval by (group_key, start, end), all intervals for one unit sit side by side in chronological start order, so you only need to keep one active strip of tape [current_start, current_end] open and either stretch its right edge with max(current_end, end) when start <= current_end, or seal it and start a new strip when a gap or new group appears.
Why do the naive approaches fail? For Task 1, slicing and summing 2 * k + 1 elements anew for each of n rows repeats almost identical additions over and over, costing O(n * k) time (billions of operations when n = 10^6 and k = 1,000). For Task 2, comparing every interval against every other interval takes O(n^2) time, and merging two intervals can widen an interval so it now touches a third one, requiring repeated passes until nothing changes.
Here is how both algorithms work on our sample inputs:
Task 1: values = [3.0, 6.0, 12.0, 0.0, 9.0], k = 1 (window width = 3)
prefix_sums = [0.0, 3.0, 9.0, 21.0, 21.0, 30.0]
i = 0: left = -1 (out of bounds) -> -1.0
i = 1: (prefix_sums[3] - prefix_sums[0]) / 3 = 21 / 3 -> 7.0
i = 2: (prefix_sums[4] - prefix_sums[1]) / 3 = 18 / 3 -> 6.0
i = 3: (prefix_sums[5] - prefix_sums[2]) / 3 = 21 / 3 -> 7.0
i = 4: right = 5 (out of bounds) -> -1.0
Task 2: intervals [("car_b", 50, 58), ("car_a", 5, 15), ("car_a", 25, 35), ("car_a", 15, 20), ("car_b", 52, 55)], num_keys = 1
Sorted: ("car_a", 5, 15), ("car_a", 15, 20), ("car_a", 25, 35), ("car_b", 50, 58), ("car_b", 52, 55)
("car_a", 5, 15) -> open ("car_a", 5, 15)
("car_a", 15, 20) -> 15 <= 15 (touches), extend end = max(15, 20) = 20
("car_a", 25, 35) -> 25 > 20 (gap), emit ("car_a", 5, 20), open ("car_a", 25, 35)
("car_b", 50, 58) -> key changed, emit ("car_a", 25, 35), open ("car_b", 50, 58)
("car_b", 52, 55) -> 52 <= 58 (nested), keep end = max(58, 55) = 58 -> flush ("car_b", 50, 58)
Complexity
Let n be the number of input rows.
centered_window_average:- Time:
O(n)(independent ofk). We scan thenrows once to buildprefix_sumswith one addition per row, and scan them a second time doing one subtraction and one division per row. - Space:
O(n).prefix_sumsstoresn + 1floats andresultstoresnoutput tuples (an in-place sliding sum could avoidprefix_sumsforO(1)auxiliary space beyond the output).
- Time:
merge_intervals:- Time:
O(n * log n). Validating and unpacking thenrows takesO(n)time, sortingntuples takesO(n * log n)comparisons, and the single left-to-right merge sweep visits each row once inO(n)time. - Space:
O(n).parsed_rowsandordered_rowsholdntuples, andmergedholds at mostnintervals when nothing overlaps.
- Time:
- Vectorized
pandasequivalents (shown below):rolling(2 * k + 1, center=True).mean()maintains a running sum in C inO(n)time andO(n)space; the grouped merge sorts inO(n * log n)time and runscummax,shift,cumsum, andgroupby().agg()inO(n)time andO(n)space.
Edge cases
- Table shorter than a full window (
n < 2 * k + 1): No row has bothkpredecessors andksuccessors, so every row receives-1.0. Whenn == 2 * k + 1, only the exact middle rowi = kreceives an average. k = 0:window_width = 1,left_index = right_index = i, and every row returns its ownvalue.- Real average equal to
-1.0: On values[-2.0, -4.0, 3.0, -5.0]withk = 1, row1has a genuine window mean of(-2.0 - 4.0 + 3.0) / 3 = -1.0, matching the out-of-bounds sentinel-1.0. The prompt specifies-1, though in production pipelinesNaNor a separateis_validboolean column avoids ambiguity. - Missing (
NaN) values invalue: With raw prefix sums, a singleNaNcontaminates every subsequent entry ofprefix_sums, turning all later windows intoNaNeven after theNaNleaves the window. Inpandas,rolling().mean()(with defaultmin_periods = 2 * k + 1) marks only the2 * k + 1windows touching thatNaNasNaN. - Extreme value magnitudes: Subtracting two huge floating-point prefix sums can suffer from catastrophic cancellation — the loss of precision when subtracting two nearly equal large floats (for example,
[1e16, 1.0, 1.0, 1.0, 1.0]withk = 1rounds1e16 + 1.0to1e16in 64-bit float, giving0.0instead of1.0for later windows).pandasrolling().mean()avoids this using compensated (Kahan) summation, an algorithm that tracks tiny rounding errors in a separate running carry variable. - Point intervals (
start == end) and exact duplicates:(5, 5)is valid (5 <= 5), and duplicate copies of(5, 5)satisfy5 <= 5so they collapse into a single(5, 5). - Empty inputs and invalid parameters: Empty input lists return
[];k < 0,num_keys < 0, wrong tuple lengths, orstart > endraiseValueError.
Common mistakes
- Calling
rolling(2 * k + 1)withoutcenter=Trueinpandas: By default,rollingcomputes a trailing window[i - 2k .. i]ending at rowi, which is shiftedkrows away from the centered window[i - k .. i + k]. - Using
.fillna(-1)blindly afterrolling().mean(): That replaces everyNaNwith-1, silently hiding genuine missing data in the middle of the table instead of only marking the firstkand lastkedge positions. - Overwriting
current_end = endinstead ofcurrent_end = max(current_end, end): Breaks whenever a short interval is nested inside a longer one —(1, 10), (2, 3), (9, 15)wrongly splits into(1, 3)and(9, 15). - Using
<instead of<=in the overlap check: Fails to merge back-to-back touching intervals like[09:00, 09:10]and[09:10, 09:20]. - Comparing against the immediately previous row's
endinpandas(df[end_col].shift(1)): If row 0 is[1, 10], row 1 is[2, 3], and row 2 is[9, 15], row 2 must compare9against10(the cumulative maximum end so far in the group), not against row 1's3. - Forgetting to group
cummax()andshift(1)by the group keys: An ungroupedshift(1)leaks the final timestamp ofvehicle_1onto the first row ofvehicle_2. - Forgetting to flush the last open interval after the
forloop: Drops the final merged interval of every non-empty input.
Alternative approaches
Vectorized pandas implementation for both tasks. In an environment with pandas and numpy, here is the idiomatic, loop-free implementation that matches solution.py on all schemas (keys = [], ["vehicle_id"], or ["vehicle_id", "event_type"]):
import numpy as np
import pandas as pd
def add_window_avg(df: pd.DataFrame, k: int) -> pd.DataFrame:
"""Task 1: centered mean of value[i-k .. i+k]; -1.0 on the first k and last k rows."""
if k < 0:
raise ValueError("k must be >= 0")
out = df.sort_values("row_id").reset_index(drop=True)
centered_mean = out["value"].rolling(window=2 * k + 1, center=True).mean()
positions = np.arange(len(out))
has_full_window = (positions >= k) & (positions < len(out) - k)
out["window_avg"] = np.where(has_full_window, centered_mean, -1.0)
return out[["row_id", "value", "window_avg"]]
def merge_event_intervals(
df: pd.DataFrame,
keys: list[str],
start_col: str,
end_col: str,
out_start: str,
out_end: str,
) -> pd.DataFrame:
"""Task 2: merge overlapping or touching intervals per group using gaps-and-islands."""
if (df[start_col] > df[end_col]).any():
raise ValueError("every interval must satisfy start <= end")
out = df.sort_values(keys + [start_col, end_col]).reset_index(drop=True)
if keys:
out["_running_end"] = out.groupby(keys, sort=False)[end_col].cummax()
prev_max_end = out.groupby(keys, sort=False)["_running_end"].shift(1)
else:
prev_max_end = out[end_col].cummax().shift(1)
# A row opens a new merged block when it is first in its group or starts strictly after prev_max_end.
is_new_block = prev_max_end.isna() | (out[start_col] > prev_max_end)
out["_block_id"] = is_new_block.cumsum()
agg_spec = {key_col: (key_col, "first") for key_col in keys}
agg_spec[out_start] = (start_col, "min")
agg_spec[out_end] = (end_col, "max")
merged = out.groupby("_block_id").agg(**agg_spec)
return merged.sort_values(keys + [out_start]).reset_index(drop=True)
Task 2 uses the gaps-and-islands pattern — a tabular technique that marks every gap (start > prev_max_end) with 1, takes a cumulative sum of those 1s to assign a unique integer ID (_block_id) to each connected "island" of overlapping rows, and aggregates min(start) and max(end) per island:
vehicle_id start end _running_end prev_max_end is_new_block _block_id
v1 1 10 10 NaN True 1
v1 2 3 10 10 False 1
v1 9 15 15 10 False 1
v1 16 20 20 15 True 2
v2 0 5 5 NaN True 3
Because every group's first row has prev_max_end = NaN (is_new_block = True), _block_id increments at every group boundary and never merges two different vehicles together.
Follow-up questions
- How can you express grouped interval merging in standard SQL using window functions? Use the exact same gaps-and-islands logic with window functions — SQL expressions (
OVER (...)) that compute running aggregates across related rows without collapsing the table. Computeprev_max_endover all preceding rows in the group, flag rows wherestart_ts > prev_max_end, take a running sum of the flags (ordering ties withis_new DESCso duplicate rows never split across islands), andGROUP BY unit_id, island:
sql
WITH ordered AS (
SELECT unit_id, start_ts, end_ts,
MAX(end_ts) OVER (
PARTITION BY unit_id
ORDER BY start_ts, end_ts
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
) AS prev_max_end
FROM events
),
flagged AS (
SELECT unit_id, start_ts, end_ts,
CASE WHEN prev_max_end IS NULL OR start_ts > prev_max_end THEN 1 ELSE 0 END AS is_new
FROM ordered
),
numbered AS (
SELECT unit_id, start_ts, end_ts,
SUM(is_new) OVER (
PARTITION BY unit_id
ORDER BY start_ts, end_ts, is_new DESC
ROWS UNBOUNDED PRECEDING
) AS island
FROM flagged
)
SELECT unit_id,
MIN(start_ts) AS merged_start_ts,
MAX(end_ts) AS merged_end_ts
FROM numbered
GROUP BY unit_id, island
ORDER BY unit_id, merged_start_ts;
-
How does the merge rule change if intervals separated by a gap of at most g time units must also coalesce? Only the boundary test changes: instead of
start <= current_end, merge wheneverstart <= current_end + g(for instanceg = timedelta(seconds=2)ondatetimeendpoints org = 2on integer timestamps). In thepandasgaps-and-islands version,is_new_blockbecomesprev_max_end.isna() | (out[start_col] > prev_max_end + g). Time and space complexity stayO(n * log n)andO(n). -
How would you adapt both functions to process an unbounded live telemetry stream? For Task 1, keep a fixed-capacity ring buffer (or
collections.deque) of the most recent2 * k + 1values and a running sum; rowi's centered average can only be emitted once rowi + karrives, introducing a fixed latency ofkrows while usingO(k)memory. For Task 2, maintain one open[current_start, current_end]state per(unit_id, signal_kind)key; if network jitter can deliver events out of order, buffer events per unit until a watermark — a timestamp threshold guaranteeing that late events older than, say, 5 minutes are no longer expected — advances pastcurrent_end.
Follow-up questions
- How can you express grouped interval merging in standard SQL using window functions?
- How does the merge rule change if intervals separated by a gap of at most g time units must also coalesce?
- How would you adapt both functions to process an unbounded live telemetry stream?
Similar questions
- Distribute Products Across Parenthesized Sums
- Connecting Doctoral Research to Production Software Engineering
- Expand Expressions into Sum-of-Products Form
- Matrix Product, Fast Power, and Matrix Fibonacci
- LRU Cache, Uniform rand10, and Square Counting
- Comparing Empirical Distributions Across Two Datasets
More WeRide interview questions
- Connecting Doctoral Research to Production Software Engineering Medium
- Expand Expressions into Sum-of-Products Form Medium
- Comparing Empirical Distributions Across Two Datasets Medium Pro
- Distribute Products Across Parenthesized Sums Medium Pro
- LRU Cache, Uniform rand10, and Square Counting Medium Pro
- Matrix Product, Fast Power, and Matrix Fibonacci Medium Pro
- Balanced Bracket Validation Medium Pro