Align Asynchronous Cycle-Count Traces Onto Shared Timestamps

Medium · Software Engineering Fundamentals · Member of Technical Staff, ML Systems · Onsite

Problem Statement

Two hardware telemetry traces, series_a and series_b, capture [timestamp, value] pairs stamped against CPU cycle counters at independent, uncoordinated times. Given both traces together with a sorted list of query cycle counts boundaries, evaluate both traces on boundaries under a shared piecewise-linear alignment contract.

def align_cpu_series(
    series_a: List[List[float]],
    series_b: List[List[float]],
    boundaries: List[float],
) -> List[List[Optional[float]]]:

Enforce the following alignment and validation rules:

  • Input ordering (ValueError): Within each trace, consecutive sample timestamps must strictly increase (curr_ts > prev_ts). Entries in boundaries must appear in non-decreasing order (boundaries[i] >= boundaries[i - 1]; identical consecutive query timestamps are permitted and produce duplicate output rows). Raise ValueError whenever either ordering requirement fails.
  • Exact hits & linear interpolation: A non-empty trace covers the closed span [first_ts, last_ts] from its earliest sample timestamp to its latest sample timestamp:
    • If query timestamp t coincides with a recorded sample [ts, val], its aligned value is val (including when the trace has only a single sample).
    • If t lies strictly inside an adjacent sample pair [t0, v0] and [t1, v1] (t0 < t < t1), compute v0 + (v1 - v0) * (t - t0) / (t1 - t0).
  • Missing values outside observed bounds: Never extrapolate beyond observed data. Whenever a trace is empty ([]), t < first_ts, or t > last_ts, report None for that trace at t.
  • Output structure: Return a list of [t, value_a, value_b] rows—one per element t of boundaries, in matching order.

Examples

Example 1

Input:
  series_a = [[100, 10], [200, 30]]
  series_b = [[150, 50], [250, 10]]
  boundaries = [100, 150, 200, 250]

Output:
  [[100, 10, None], [150, 20.0, 50], [200, 30, 30.0], [250, None, 10]]

At cycle 100, series_a begins at 10 while series_b has not started (None). At 150, series_a is halfway across [100, 200] (20.0) and series_b hits 50. At 200, series_a reaches 30 and series_b is halfway between 50 and 10 (30.0). At 250, series_a has already ended (None) and series_b hits 10.

Example 2

Input:
  series_a = [[0, 4], [6, 16], [12, 10]]
  series_b = [[3, 20], [9, 32]]
  boundaries = [2, 3, 6, 9, 12]

Output:
  [[2, 8.0, None], [3, 10.0, 20], [6, 16, 26.0], [9, 13.0, 32], [12, 10, None]]

series_a rises at +2 per cycle on [0, 6] (giving 8.0 at t = 2, 10.0 at t = 3, and 16 at t = 6) and falls at -1 per cycle on [6, 12] (giving 13.0 at t = 9 and 10 at t = 12). Meanwhile series_b spans [3, 9], producing None at t = 2 and t = 12, exact values 20 and 32 at its endpoints, and midpoint 26.0 at t = 6.

Example 3

Input:
  series_a = [[10, 6], [14, 14]]
  series_b = [[8, 0], [16, 24]]
  boundaries = [6, 8, 10, 12, 16]

Output:
  [[6, None, None], [8, None, 0], [10, 6, 6.0], [12, 10.0, 12.0], [16, None, 24]]

Query 6 precedes both traces ([6, None, None]). Across [10, 14], both traces overlap and produce interpolated pairs, before series_a ends prior to t = 16.

Constraints

  • 0 <= len(series_a), len(series_b), len(boundaries) <= 10^5
  • Valid traces satisfy series[i][0] > series[i - 1][0] for all i >= 1; non-increasing timestamps must raise ValueError.
  • Valid query grids satisfy boundaries[i] >= boundaries[i - 1] for all i >= 1; unsorted boundaries must raise ValueError.
  • The two traces may share zero timestamps, overlap partially, or be completely disjoint.

Step-by-step walkthrough

  1. Lock down the alignment contract

    Before coding, let's summarize the exact rules that govern every query timestamp in boundaries:

    • Target timestamps: Supplied by the caller in boundaries, sorted in non-decreasing order (boundaries[i] >= boundaries[i - 1]).
    • Instantaneous value via linear segments: Each query t reads an instantaneous value off the straight-line segments connecting consecutive [timestamp, value] samples (piecewise-linear interpolation).
    • No extrapolation outside observed spans: A non-empty trace is defined only across [first_ts, last_ts], both endpoints included. Queries strictly below first_ts or strictly above last_ts evaluate to None.
    • Exact sample matches: Whenever t equals a sample's timestamp, return that sample's recorded value directly.
    • Row layout: Emit [t, value_a, value_b] for each t in boundaries, preserving order.

    Here is Example 1 (series_a = [[100, 10], [200, 30]], series_b = [[150, 50], [250, 10]], boundaries = [100, 150, 200, 250]) plotted on a shared cycle axis:

    Cycle t:        100          150          200          250
                     |            |            |            |
    Series A:    (100,10)------[t=150]-----(200,30)        None     (A ends at 200)
                  val=10       val=20.0     val=30
    
    Series B:       None       (150,50)----[t=200]-----(250,10)     (B starts at 150)
                                val=50     val=30.0     val=10
    
    Output rows: [100,10,None] [150,20,50] [200,30,30] [250,None,10]
    

    We also guard against malformed inputs by raising ValueError whenever timestamps inside a trace fail to strictly increase (curr_ts <= prev_ts) or boundaries decreases (boundaries[i] < boundaries[i - 1]).

  2. Why scanning from scratch per boundary is too slow

    When a query t falls inside [left_ts, right_ts], how far across the interval (right_ts - left_ts) does t sit?

    fraction     = (t - left_ts) / (right_ts - left_ts)
    interpolated = left_val + (right_val - left_val) * fraction
    

    At t == left_ts, fraction is 0 (left_val); halfway across, fraction is 0.5 (the midpoint value).

    If we searched from index 0 on every single query t to locate its bracketing segment, B boundaries across n samples would take O(B * n) work. Hardware cycle traces routinely contain hundreds of thousands of readings and thousands of query points, turning B * n into billions of redundant comparisons.

  3. Key idea: advance one segment pointer forward

    Both series and boundaries are ordered in non-decreasing time. Once boundaries[i] lands in segment seg_idx, the next query boundaries[i + 1] >= boundaries[i] can only land in segment seg_idx or a later segment—never an earlier one.

    Keeping a single index seg_idx per trace that only steps rightward eliminates all backtracking:

    series_a:    [0]---------[6]---------[12]
    boundaries:     2   3   6       9       12
    seg_idx:        0   0   1  -->  1  -->  2   (never resets to 0!)
    

    Across all B queries, seg_idx increments at most n - 1 times total, cutting the runtime per trace from O(B * n) down to O(n + B). Evaluating series_a and series_b independently with the same helper also handles completely disjoint or unshared timestamps automatically.

  4. Validate timestamps and boundary order

    Before sweeping, _check_series verifies strictly increasing sample timestamps. Rejecting curr_ts <= prev_ts prevents both zero-width division (right_ts - left_ts == 0) on duplicate timestamps and silent corruption when a hardware cycle register wraps or resets backward.

    def _check_series(series: List[List[float]], name: str) -> None:
        """Verify timestamps strictly increase; equal or decreasing timestamps break segments."""
        # series: list of [timestamp, value] pairs, e.g. [[0, 4], [6, 16], [12, 10]]
        for i in range(1, len(series)):
            prev_ts = series[i - 1][0]
            curr_ts = series[i][0]
            # Reject <= (not just <): duplicate timestamps make segment width 0 (division by zero),
            # and decreasing timestamps typically signal a CPU cycle counter reset or wraparound.
            if curr_ts <= prev_ts:
                raise ValueError(f"{name}: timestamps must strictly increase (index {i})")
    
  5. Interpolate one trace in a single pass

    Inside _values_at(series, boundaries), an empty trace immediately returns [None] * len(boundaries). Otherwise each query t runs through four clean stages:

    1. Range check (t < first_ts or t > last_ts): Append None. Any query reaching stage 2 is guaranteed to satisfy first_ts <= t <= last_ts.
    2. Advance seg_idx: While seg_idx + 1 < len(series) and series[seg_idx + 1][0] <= t, increment seg_idx. Using <= steps seg_idx directly onto a sample whenever t matches that sample's timestamp.
    3. Exact sample hit (t == left_ts): Append left_val verbatim. This avoids floating-point rounding drift and safely handles t == last_ts (where seg_idx == len(series) - 1, so series[seg_idx + 1] does not exist).
    4. Linear interpolation: Because t <= last_ts and t != left_ts, seg_idx + 1 is guaranteed to exist with left_ts < t < right_ts. Compute fraction and interpolated.
    def _values_at(series: List[List[float]], boundaries: List[float]) -> List[Optional[float]]:
        """Interpolate `series` at each sorted boundary; return None outside [first_ts, last_ts]."""
        if len(series) == 0:
            return [None] * len(boundaries)
    
        first_ts = series[0][0]
        last_ts = series[-1][0]
    
        # values: one interpolated float (or None if out of range) per boundary timestamp
        values: List[Optional[float]] = []
        # seg_idx: index of the left sample [left_ts, left_val] bracketing the current boundary;
        # only moves forward because both `series` and `boundaries` are sorted.
        seg_idx = 0
    
        for t in boundaries:
            # Phase 1: Out-of-range check. Strict < and > keep exact endpoints [first_ts, last_ts] valid,
            # while reporting None outside the observed span instead of extrapolating.
            if t < first_ts or t > last_ts:
                values.append(None)
                continue
    
            # Phase 2: Advance seg_idx while the next sample is at or before t.
            # Using <= lands seg_idx directly on the sample whenever t matches a sample timestamp.
            while seg_idx + 1 < len(series) and series[seg_idx + 1][0] <= t:
                seg_idx += 1
    
            left_ts, left_val = series[seg_idx]
    
            # Phase 3: Exact sample hit. Returning left_val directly avoids floating-point rounding
            # and safely handles t == last_ts (where series[seg_idx + 1] does not exist).
            if t == left_ts:
                values.append(left_val)
                continue
    
            # Phase 4: Linear interpolation inside (left_ts, right_ts).
            # Invariant: left_ts < t < right_ts and seg_idx + 1 < len(series) because t <= last_ts and t != left_ts.
            right_ts, right_val = series[seg_idx + 1]
            fraction = (t - left_ts) / (right_ts - left_ts)
            interpolated = left_val + (right_val - left_val) * fraction
            values.append(interpolated)
    
        return values
    
  6. Trace Example 2 and assemble the aligned rows

    Let's walk through Example 2 (series_a = [[0, 4], [6, 16], [12, 10]], series_b = [[3, 20], [9, 32]], boundaries = [2, 3, 6, 9, 12]):

    Boundary t | Series A (span [0, 12])                      | Series B (span [3, 9])
    -----------+----------------------------------------------+-------------------------------------
    t = 2      | seg_idx=0, seg [0,6]: 4 + 12*(2/6) = 8.0     | 2 < first_ts (3) -> None
    t = 3      | seg_idx=0, seg [0,6]: 4 + 12*(3/6) = 10.0    | seg_idx=0, exact hit t==3 -> 20
    t = 6      | seg_idx->1, exact hit t==6 -> 16             | seg_idx=0, seg [3,9]: 20 + 12*(3/6) = 26.0
    t = 9      | seg_idx=1, seg [6,12]: 16 + (-6)*(3/6) = 13.0| seg_idx->1, exact hit t==9 -> 32
    t = 12     | seg_idx->2, exact hit t==12 -> 10            | 12 > last_ts (9) -> None
    

    Pairing [boundaries[i], values_a[i], values_b[i]] yields [[2, 8.0, None], [3, 10.0, 20], [6, 16, 26.0], [9, 13.0, 32], [12, 10, None]], matching Example 2.

    def align_cpu_series(
        series_a: List[List[float]],
        series_b: List[List[float]],
        boundaries: List[float],
    ) -> List[List[Optional[float]]]:
        # Ensure boundaries are non-decreasing so the single forward pointer in _values_at stays valid.
        # Equal consecutive boundaries (curr < prev is False) are allowed and simply repeat the row.
        for i in range(1, len(boundaries)):
            if boundaries[i] < boundaries[i - 1]:
                raise ValueError("boundaries must be sorted in non-decreasing order")
    
        _check_series(series_a, "series_a")
        _check_series(series_b, "series_b")
    
        # Evaluate both series independently on the shared boundary timestamps.
        values_a = _values_at(series_a, boundaries)
        values_b = _values_at(series_b, boundaries)
    
        # rows: list of [boundary_ts, val_a_or_None, val_b_or_None] aligned to `boundaries`
        rows: List[List[Optional[float]]] = []
        for i in range(len(boundaries)):
            rows.append([boundaries[i], values_a[i], values_b[i]])
        return rows
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def _check_series(series: List[List[float]], name: str) -> None:
        """Verify timestamps strictly increase; equal or decreasing timestamps break segments."""
        # series: list of [timestamp, value] pairs, e.g. [[0, 4], [6, 16], [12, 10]]
        for i in range(1, len(series)):
            prev_ts = series[i - 1][0]
            curr_ts = series[i][0]
            # Reject <= (not just <): duplicate timestamps make segment width 0 (division by zero),
            # and decreasing timestamps typically signal a CPU cycle counter reset or wraparound.
            if curr_ts <= prev_ts:
                raise ValueError(f"{name}: timestamps must strictly increase (index {i})")
    
    
    def _values_at(series: List[List[float]], boundaries: List[float]) -> List[Optional[float]]:
        """Interpolate `series` at each sorted boundary; return None outside [first_ts, last_ts]."""
        if len(series) == 0:
            return [None] * len(boundaries)
    
        first_ts = series[0][0]
        last_ts = series[-1][0]
    
        # values: one interpolated float (or None if out of range) per boundary timestamp
        values: List[Optional[float]] = []
        # seg_idx: index of the left sample [left_ts, left_val] bracketing the current boundary;
        # only moves forward because both `series` and `boundaries` are sorted.
        seg_idx = 0
    
        for t in boundaries:
            # Phase 1: Out-of-range check. Strict < and > keep exact endpoints [first_ts, last_ts] valid,
            # while reporting None outside the observed span instead of extrapolating.
            if t < first_ts or t > last_ts:
                values.append(None)
                continue
    
            # Phase 2: Advance seg_idx while the next sample is at or before t.
            # Using <= lands seg_idx directly on the sample whenever t matches a sample timestamp.
            while seg_idx + 1 < len(series) and series[seg_idx + 1][0] <= t:
                seg_idx += 1
    
            left_ts, left_val = series[seg_idx]
    
            # Phase 3: Exact sample hit. Returning left_val directly avoids floating-point rounding
            # and safely handles t == last_ts (where series[seg_idx + 1] does not exist).
            if t == left_ts:
                values.append(left_val)
                continue
    
            # Phase 4: Linear interpolation inside (left_ts, right_ts).
            # Invariant: left_ts < t < right_ts and seg_idx + 1 < len(series) because t <= last_ts and t != left_ts.
            right_ts, right_val = series[seg_idx + 1]
            fraction = (t - left_ts) / (right_ts - left_ts)
            interpolated = left_val + (right_val - left_val) * fraction
            values.append(interpolated)
    
        return values
    
    
    def align_cpu_series(
        series_a: List[List[float]],
        series_b: List[List[float]],
        boundaries: List[float],
    ) -> List[List[Optional[float]]]:
        # Ensure boundaries are non-decreasing so the single forward pointer in _values_at stays valid.
        # Equal consecutive boundaries (curr < prev is False) are allowed and simply repeat the row.
        for i in range(1, len(boundaries)):
            if boundaries[i] < boundaries[i - 1]:
                raise ValueError("boundaries must be sorted in non-decreasing order")
    
        _check_series(series_a, "series_a")
        _check_series(series_b, "series_b")
    
        # Evaluate both series independently on the shared boundary timestamps.
        values_a = _values_at(series_a, boundaries)
        values_b = _values_at(series_b, boundaries)
    
        # rows: list of [boundary_ts, val_a_or_None, val_b_or_None] aligned to `boundaries`
        rows: List[List[Optional[float]]] = []
        for i in range(len(boundaries)):
            rows.append([boundaries[i], values_a[i], values_b[i]])
        return rows
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture two hardware probes logging CPU metrics at uncoordinated moments, and plotting both traces on shared graph paper by drawing straight lines dot-to-dot between consecutive samples. This dot-to-dot model is piecewise-linear interpolation, which estimates a metric at any intermediate timestamp along the straight line joining its nearest left and right samples. To compare both probes on one schedule, we place vertical markers at every timestamp in boundaries and read off where each curve crosses the marker—returning None wherever a trace has not started yet or has already finished, instead of extrapolating (projecting lines past the first or last recorded reading).

Scanning an entire n-sample trace from index 0 for every one of the B query timestamps repeats nearly the entire search each time, costing O(B * n) operations. Instead, we use a two-pointer scan—an algorithm that walks two sorted sequences with an index that only moves forward—so our segment pointer seg_idx never backtracks from one query timestamp to the next.

Trace Example 1 with series_a = [[100, 10], [200, 30]], series_b = [[150, 50], [250, 10]], and boundaries = [100, 150, 200, 250]: 1. At t = 100: series_a hits its initial sample (10), whereas series_b has not begun (100 < 150 -> None), yielding [100, 10, None]. 2. At t = 150: series_a sits halfway across [100, 200], giving 10 + (30 - 10) * (50 / 100) = 20.0; series_b hits (150, 50), yielding [150, 20.0, 50]. 3. At t = 200: series_a advances seg_idx to (200, 30) for 30; series_b sits halfway across [150, 250], giving 50 + (10 - 50) * (50 / 100) = 30.0, yielding [200, 30, 30.0]. 4. At t = 250: series_a has ended (250 > 200 -> None), whereas series_b hits (250, 10), yielding [250, None, 10].

Complexity

Let n_a be len(series_a), n_b be len(series_b), and B be len(boundaries).

  • Time: O(n_a + n_b + B). Validating ordering scans each input once, and inside _values_at the pointer seg_idx increments at most n - 1 times total across all B queries while each query performs O(1) arithmetic.
  • Space: O(B) to hold values_a, values_b, and the B output rows (only scalar variables are used during the sweep).

Edge cases

  • Empty trace ([]): Contains no samples, so every query timestamp receives None for that trace.
  • Single-sample trace ([[5, 7]]): Defined solely at t = 5 (returning 7); any query t != 5 falls outside [5, 5] and receives None.
  • Queries matching first_ts or last_ts: Both endpoints are inclusive and return the exact recorded value without indexing series[seg_idx + 1].
  • Queries outside [first_ts, last_ts]: Produce None rather than extending the edge slope.
  • Unshared or disjoint spans: Handled seamlessly because series_a and series_b are evaluated independently on boundaries.
  • Duplicate entries in boundaries: Permitted (boundaries[i] < boundaries[i - 1] is False on ties) and emit identical consecutive rows.
  • Large cycle counts (10^12+): Python int arithmetic computes t - left_ts and right_ts - left_ts exactly; when ingesting 64-bit float arrays (float64, which represents integers exactly only up to 2^53), subtract an integer base cycle offset before converting to float.
  • Non-increasing trace timestamps or unsorted boundaries: Raise ValueError upfront instead of dividing by zero or misplacing seg_idx.

Common mistakes

  • Extrapolating past first_ts or last_ts: Extending the first or last segment's slope invents unmeasured values instead of returning None.
  • Using <= / >= in the out-of-bounds guard (t <= first_ts): Wrongly turns exact endpoint hits into None.
  • Resetting seg_idx = 0 per query: Degrades the O(n + B) sweep back to O(B * n).
  • Evaluating the division formula when t == left_ts: Introduces unnecessary float rounding and triggers IndexError on series[seg_idx + 1] when t == last_ts.
  • Outputting at the union of sample timestamps: Ignores the caller-supplied boundaries schedule.

Alternative approaches

  • Per-query binary search (bisect): Binary search repeatedly halves a sorted array to locate a target position in O(log n) comparisons. Running it per query takes O(B log n) time, works even on unsorted boundaries, and beats a linear scan when B is tiny relative to n (such as 5 queries across 10 million samples).
  • NumPy np.interp: Runs in vectorized C, though np.interp clamps out-of-bounds queries to endpoint values by default, requiring left=np.nan, right=np.nan plus NaN-to-None conversion.

Follow-up questions

  • How would you modify the pass if each interval [b_i, b_{i+1}] required a time-weighted mean instead of an instantaneous value at b_i? The time-weighted mean of a continuous curve across [b_i, b_{i+1}] equals the area under the curve divided by b_{i+1} - b_i. Because each piece is linear, compute the area via the trapezoidal rule—where the area under a line segment over [lo, hi] is (hi - lo) * (val_lo + val_hi) / 2—clipped to [b_i, b_{i+1}], advancing a single segment pointer across adjacent windows in O(n + B) time (returning None whenever [b_i, b_{i+1}] is not fully covered by [first_ts, last_ts]).
def window_average(series, start, end):
    """Time-weighted mean of piecewise-linear `series` on [start, end], or None if uncovered."""
    if len(series) == 0 or end <= start or start < series[0][0] or end > series[-1][0]:
        return None
    total_area = 0.0
    for i in range(len(series) - 1):
        left_ts, left_val = series[i]
        right_ts, right_val = series[i + 1]
        lo = max(left_ts, start)
        hi = min(right_ts, end)
        if lo < hi:
            slope = (right_val - left_val) / (right_ts - left_ts)
            val_lo = left_val + slope * (lo - left_ts)
            val_hi = left_val + slope * (hi - left_ts)
            total_area += (hi - lo) * (val_lo + val_hi) / 2.0
    return total_area / (end - start)
  • How would you adapt this into a streaming operator when interpolating at timestamp t must wait for the next sample after t to arrive? Keep only the latest observed sample (prev_ts, prev_val) per stream alongside a FIFO queue of pending query timestamps. Each time a new sample (curr_ts, curr_val) arrives, every queued query t <= curr_ts now has its right endpoint and resolves immediately (None if t preceded the stream's very first sample, or interpolated across [prev_ts, curr_ts]), emitting [t, val_a, val_b] once both streams resolve t. To prevent unbounded memory growth if one probe goes silent, enforce a watermark—a timestamp cutoff declaring no valid readings older than a timeout will arrive—to flush stalled queries with None.
  • How can an ingestion pipeline tell apart fixed-width cycle-counter wraparound from an unexpected counter reset? Whenever curr_ts <= prev_ts, test whether counter wraparound—where a W-bit hardware register overflows past 2^W - 1 back through 0—explains the drop by checking whether (curr_ts + 2^W) - prev_ts matches the expected sampling cadence in cycles. If it matches, add 2^W to unwrap subsequent timestamps into a continuous monotone timeline; if the delta is erratic (caused by a reboot or thread migration across unsynchronized cores), split the trace at the discontinuity and report None across the gap instead of interpolating across invalid data. Note that a 32-bit counter at 4 GHz wraps roughly every 1.07 seconds, whereas a 64-bit counter runs for ~146 years.

Follow-up questions

Similar questions

More Gimlet Labs interview questions

All 4 Gimlet Labs questions →