KatInterview

Align Time Series with Linear Interpolation

Arrays & HashingAuto-graded · 23 test cases
MediumAuto-gradedArrays & Hashinginterpolationbinary-searchtime-series

Last updated

Tests piecewise-linear interpolation, binary search, and boundary handling for sampling two time series at common timestamps.

You are given two time series, each represented as a list of [timestamp, value] pairs with strictly increasing timestamps. Each series defines a piecewise-linear function: between any two consecutive samples, the value changes linearly.

Your task is to sample both series at a set of query timestamps (boundaries) and return the interpolated or exact values at those points.

Rules

  • If a query timestamp matches a sample timestamp exactly, return the sample's value.
  • If a query timestamp falls between two consecutive samples, interpolate linearly.
  • If a query timestamp is outside a series' sampled range (before the first timestamp or after the last timestamp), return None for that series.
  • Each output row corresponds to one boundary timestamp and contains [timestamp, value_from_series_a, value_from_series_b].

Constraints

  • 0 ≤ len(series_a), len(series_b) ≤ 10^4
  • 1 ≤ len(boundaries) ≤ 10^4
  • All timestamps within a series are strictly increasing.
  • Boundary timestamps are sorted in ascending order.
  • Timestamp and value are floats; interpolation must use floating-point division.

Examples

Example 1

Input: sample_time_series([[0, 0], [10, 10]], [[5, 20], [15, 40]], [0, 5, 10, 15])

Output: [[0, 0, None], [5, 5, 20], [10, 10, 30], [15, None, 40]]

Example 2

Input: sample_time_series([[0, 2], [4, 6], [8, 10]], [[2, 10], [6, 18]], [1, 2, 3, 6, 8])

Output: [[1, 3, None], [2, 4, 10], [3, 5, 12], [6, 8, 18], [8, 10, None]]

Example 3

Input: sample_time_series([[1, 5], [3, 9]], [[0, 0], [4, 8]], [0, 1, 2, 3, 4])

Output: [[0, None, 0], [1, 5, 2], [2, 7, 4], [3, 9, 6], [4, None, 8]]

Hints

Hint 1

Use binary search to locate the segment bracketing each query timestamp without rescanning from the start.

Hint 2

Handle exact matches separately before attempting interpolation.

Hint 3

A query outside a series' range [first_timestamp, last_timestamp] must yield None for that series.