Piecewise Linear Curve Evaluator

Medium · Coding & Algorithms · Quantitative Researcher · Technical Screen

Problem Statement

Given n unsorted 2D anchor points knots[i] = [x_i, y_i] whose x-coordinates are all distinct, build and evaluate a continuous piecewise linear function L(x) across a batch of queries:

def interpolate(knots: List[List[float]], queries: List[float]) -> List[float]:

Let (x_0, y_0), (x_1, y_1), ..., (x_{n-1}, y_{n-1}) denote the knots ordered by strictly increasing x-coordinate, with x_min = x_0 and x_max = x_{n-1}:

  • Interior and knot values (x_min <= x <= x_max): Join each consecutive sorted pair (x_i, y_i) and (x_{i+1}, y_{i+1}) with a straight line segment. If x equals x_i, L(x_i) = y_i; if x_i < x < x_{i+1}, L(x) lies on the segment connecting (x_i, y_i) to (x_{i+1}, y_{i+1}).
  • Left boundary extrapolation (x < x_min): Continue along the infinite straight line determined by the two leftmost sorted knots (x_0, y_0) and (x_1, y_1).
  • Right boundary extrapolation (x > x_max): Continue along the infinite straight line determined by the two rightmost sorted knots (x_{n-2}, y_{n-2}) and (x_{n-1}, y_{n-1}).

Return a list answers of length len(queries) in the exact input order of queries, where answers[j] = L(queries[j]). Aim for O((n + q) log n) time, where q = len(queries).

Examples

Example 1

Input:  knots = [[2, 4], [6, 12], [14, 8]], queries = [4, 6, 10]
Output: [8.0, 12.0, 10.0]
  • Between (2, 4) and (6, 12) the slope is (12 - 4) / (6 - 2) = 2.0, so L(4) = 4 + 2.0 * (4 - 2) = 8.0.
  • x = 6 lands directly on the middle knot (6, 12), returning 12.0.
  • Between (6, 12) and (14, 8) the slope is (8 - 12) / (14 - 6) = -0.5, so L(10) = 12 + (-0.5) * (10 - 6) = 10.0.

Example 2

Input:  knots = [[6, 12], [14, 8], [2, 4]], queries = [18, -1]
Output: [6.0, -2.0]

Sorting the knots by x gives (2, 4), (6, 12), (14, 8) (x_min = 2, x_max = 14). - For q = 18 > 14, extend the rightmost segment through (6, 12) and (14, 8) (slope -0.5): L(18) = 8 + (-0.5) * (18 - 14) = 6.0. - For q = -1 < 2, extend the leftmost segment through (2, 4) and (6, 12) (slope 2.0): L(-1) = 4 + 2.0 * (-1 - 2) = -2.0.

Constraints

  • 2 <= len(knots) <= 100,000
  • 1 <= len(queries) <= 100,000
  • -10^9 <= x_i, y_i, queries[j] <= 10^9, each given with at most 6 digits after the decimal point
  • All knot x-coordinates x_i are strictly distinct
  • Queries may coincide with a knot, lie strictly between knots, or lie outside [x_min, x_max]
  • Each output entry is accepted within an absolute or relative tolerance of 10^-6

Step-by-step walkthrough

  1. Understand the curve and extrapolation rule

    We are given n >= 2 unsorted 2D points knots[i] = [x_i, y_i] with distinct x-coordinates, plus a list of queries. Once we sort the knots from smallest x to largest x, connecting each adjacent pair with a straight line segment defines a piecewise linear function L(x) across [x_min, x_max].

    Outside [x_min, x_max], L(x) continues along the outermost line segments (linear extrapolation): - For x < x_min, follow the straight line passing through the two leftmost sorted knots (x_0, y_0) and (x_1, y_1). - For x > x_max, follow the straight line passing through the two rightmost sorted knots (x_{n-2}, y_{n-2}) and (x_{n-1}, y_{n-1}).

              y
             12 |        * (6, 12)
                |       /   \
              8 |      .      * (14, 8)
              4 |    * (2, 4)    \
              0 +----+------------+----> x
               /                   \
      q = -1 -> -2.0          q = 18 -> 6.0
      (extends segment 0)     (extends last segment)
    

    We must return [L(q) for q in queries] in the exact order the queries were supplied.

  2. Why scanning per query is too slow

    A straightforward brute-force approach sorts knots once and then, for each query q, loops through all n - 1 segments to locate which [x_i, x_{i+1}] contains q. With n = 100,000 knots and q = 100,000 queries, n * q reaches 10^10 operations — tens of seconds in Python.

    Because the sorted x-coordinates sit in strictly increasing order, we can replace that linear scan with binary search (repeatedly halving the search interval to find where q falls in at most ceil(log2(n)) <= 17 comparisons). Sorting once takes O(n log n) and answering all q queries takes O(q log n), meeting the expected O((n + q) log n) runtime.

  3. Unify interpolation and extrapolation with a clamped segment index

    Notice that n sorted knots define n - 1 line segments, numbered 0, 1, ..., n - 2, where segment i connects knot i to knot i + 1. Every possible query — whether inside or outside [x_min, x_max] — lies on the line of one of those n - 1 segments:

    Sorted knots:     x_0 -------- x_1 -------- x_2 -------- x_3   (n = 4, segments 0..2)
    Segment index:         seg 0        seg 1        seg 2
    
    Query zone        bisect_right(xs, q) - 1    Target segment
    --------------    -----------------------    --------------
    q < x_0                  -1                  0      (leftmost segment)
    x_0 <= q < x_1            0                  0
    x_1 <= q < x_2            1                  1
    x_2 <= q < x_3            2                  2
    q >= x_3                  3 (= n - 1)        2 (= n - 2, rightmost segment)
    

    Python's bisect_right(xs, query_x) counts how many knots satisfy x <= query_x. Subtracting 1 gives knot_idx, the index of the rightmost knot at or to the left of query_x (or -1 when query_x < x_0). Clamping knot_idx into [0, n - 2] via min(max(knot_idx, 0), n - 2) automatically routes left extrapolation to segment 0, right extrapolation to segment n - 2, and interior points to their enclosing segment — all with one point-slope formula!

  4. Sort the knots once and split `xs` and `ys`

    Calling sorted(knots) sorts [x, y] pairs by x first without mutating the caller's list (and since all x values are distinct, y never breaks ties). Splitting the sorted points into two flat lists xs and ys lets bisect_right search xs directly as plain floats.

    from typing import List, Tuple
    
    
    def split_sorted_knots(knots: List[List[float]]) -> Tuple[List[float], List[float]]:
        """Sort `[x, y]` knots by `x` and split them into parallel `xs` and `ys` lists."""
        # xs: strictly increasing x-coordinates, e.g. [2.0, 6.0, 14.0]
        # ys: matching y-coordinates at each knot, e.g. [4.0, 12.0, 8.0]
        xs: List[float] = []
        ys: List[float] = []
        for x, y in sorted(knots):
            xs.append(x)
            ys.append(y)
        return xs, ys
    
  5. Evaluate a single query and preserve query order

    Before clamping, we check if knot_idx >= 0 and xs[knot_idx] == query_x: when a query lands directly on any knot (including x_max, where knot_idx == n - 1), returning float(ys[knot_idx]) gives the exact stored height with zero floating-point rounding.

    Otherwise we clamp seg_idx = min(max(knot_idx, 0), len(xs) - 2). That clamp is critical in Python: without max(knot_idx, 0), knot_idx == -1 would silently read xs[-1] (the last knot!) instead of raising an error, and without min(..., len(xs) - 2), seg_idx + 1 would raise IndexError when query_x > x_max.

    Finally, interpolate loops over queries in their given order and collects each result.

    from typing import List
    from bisect import bisect_right
    
    
    def evaluate_query(xs: List[float], ys: List[float], query_x: float) -> float:
        """Evaluate the piecewise linear curve (with end-segment extrapolation) at `query_x`."""
        # Step 1: Locate the rightmost knot with x <= query_x (gives -1 if query_x < xs[0]).
        knot_idx = bisect_right(xs, query_x) - 1
    
        # Step 2: If query_x lands directly on a knot (including x_max), return its exact y.
        if knot_idx >= 0 and xs[knot_idx] == query_x:
            return float(ys[knot_idx])
    
        # Step 3: Clamp into [0, n - 2] so left extrapolation uses segment 0
        # and right extrapolation uses the final segment (n - 2).
        # Without clamping, knot_idx == -1 would hit Python's negative indexing xs[-1]!
        last_segment_idx = len(xs) - 2
        seg_idx = min(max(knot_idx, 0), last_segment_idx)
    
        # Step 4: Evaluate the line through (xs[seg_idx], ys[seg_idx]) and (xs[seg_idx+1], ys[seg_idx+1]).
        # All x-coordinates are distinct, so (x1 - x0) is strictly positive and never divides by zero.
        x0, y0 = xs[seg_idx], ys[seg_idx]
        x1, y1 = xs[seg_idx + 1], ys[seg_idx + 1]
        slope = (y1 - y0) / (x1 - x0)
        return y0 + slope * (query_x - x0)
    
    
    def interpolate(knots: List[List[float]], queries: List[float]) -> List[float]:
        """Return `[L(q) for q in queries]` in the original query order."""
        xs, ys = split_sorted_knots(knots)
        # Answer queries in arrival order rather than sorting `queries` in place.
        answers: List[float] = []
        for query_x in queries:
            answers.append(evaluate_query(xs, ys, query_x))
        return answers
    
  6. Trace Example 1 and Example 2 step by step

    Input knots: [[6, 12], [14, 8], [2, 4]]   (n = 3, last_segment_idx = 1)
    After split_sorted_knots:
      xs = [2,  6, 14]
      ys = [4, 12,  8]
    
    Query q = 6 (exact knot from Example 1):
      bisect_right(xs, 6) = 2   ->  knot_idx = 1
      xs[1] == 6 is True        ->  return float(ys[1]) = 12.0
    
    Query q = 18 (right extrapolation from Example 2):
      bisect_right(xs, 18) = 3  ->  knot_idx = 2 (xs[2] = 14 != 18)
      clamp(2, 0, 1)            ->  seg_idx = 1  (points (6, 12) and (14, 8))
      slope = (8 - 12) / (14 - 6) = -0.5
      answer = 12 + (-0.5) * (18 - 6) = 6.0
    
    Query q = -1 (left extrapolation from Example 2):
      bisect_right(xs, -1) = 0  ->  knot_idx = -1
      clamp(-1, 0, 1)           ->  seg_idx = 0  (points (2, 4) and (6, 12))
      slope = (12 - 4) / (6 - 2) = 2.0
      answer = 4 + 2.0 * (-1 - 2) = -2.0
    

    Notice that on the right-extrapolation line through (6, 12) and (14, 8), anchoring at (6, 12) (12 + (-0.5) * (18 - 6) = 6.0) yields the exact same value as anchoring at (14, 8) (8 + (-0.5) * (18 - 14) = 6.0).

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    from bisect import bisect_right
    
    
    def split_sorted_knots(knots: List[List[float]]) -> Tuple[List[float], List[float]]:
        """Sort `[x, y]` knots by `x` and split them into parallel `xs` and `ys` lists."""
        # xs: strictly increasing x-coordinates, e.g. [2.0, 6.0, 14.0]
        # ys: matching y-coordinates at each knot, e.g. [4.0, 12.0, 8.0]
        xs: List[float] = []
        ys: List[float] = []
        for x, y in sorted(knots):
            xs.append(x)
            ys.append(y)
        return xs, ys
    
    
    def evaluate_query(xs: List[float], ys: List[float], query_x: float) -> float:
        """Evaluate the piecewise linear curve (with end-segment extrapolation) at `query_x`."""
        # Step 1: Locate the rightmost knot with x <= query_x (gives -1 if query_x < xs[0]).
        knot_idx = bisect_right(xs, query_x) - 1
    
        # Step 2: If query_x lands directly on a knot (including x_max), return its exact y.
        if knot_idx >= 0 and xs[knot_idx] == query_x:
            return float(ys[knot_idx])
    
        # Step 3: Clamp into [0, n - 2] so left extrapolation uses segment 0
        # and right extrapolation uses the final segment (n - 2).
        # Without clamping, knot_idx == -1 would hit Python's negative indexing xs[-1]!
        last_segment_idx = len(xs) - 2
        seg_idx = min(max(knot_idx, 0), last_segment_idx)
    
        # Step 4: Evaluate the line through (xs[seg_idx], ys[seg_idx]) and (xs[seg_idx+1], ys[seg_idx+1]).
        # All x-coordinates are distinct, so (x1 - x0) is strictly positive and never divides by zero.
        x0, y0 = xs[seg_idx], ys[seg_idx]
        x1, y1 = xs[seg_idx + 1], ys[seg_idx + 1]
        slope = (y1 - y0) / (x1 - x0)
        return y0 + slope * (query_x - x0)
    
    
    def interpolate(knots: List[List[float]], queries: List[float]) -> List[float]:
        """Return `[L(q) for q in queries]` in the original query order."""
        xs, ys = split_sorted_knots(knots)
        # Answer queries in arrival order rather than sorting `queries` in place.
        answers: List[float] = []
        for query_x in queries:
            answers.append(evaluate_query(xs, ys, query_x))
        return answers
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine plotting hourly temperature readings on graph paper and connecting consecutive dots with a straight ruler. For any time between your first and last measurement, you read the height on the line segment directly above that time — a technique called piecewise linear interpolation (constructing a continuous curve by joining sorted data points (x_i, y_i) with straight line segments). If someone asks about a time before your earliest reading or after your latest one, you keep your ruler lined up with the two leftmost dots (or the two rightmost dots) and extend that straight line outward — linear extrapolation (predicting values outside [x_min, x_max] by continuing the boundary segment's slope).

Why do naive approaches fall short? Scanning all n segments for every query takes O(n * q) operations — up to 10^10 checks when n = 100,000 and q = 100,000, which times out in Python. Reaching for numpy.interp also fails because it clamps out-of-range queries flat to y_0 and y_{n-1} instead of extending the boundary slope! Instead, sorting the knots once and locating each query's bracket with binary search (repeatedly halving the sorted x list in O(log n) steps via bisect_right) finds the right segment in at most 17 comparisons, and clamping the segment index to [0, n - 2] lets one point-slope formula handle interior interpolation and both extrapolations uniformly.

Here is how knots = [[6, 12], [14, 8], [2, 4]] evaluates queries = [-1, 6, 18]:

Sorted knots: xs = [2, 6, 14], ys = [4, 12, 8]   (2 segments: seg 0 on [2, 6], seg 1 on [6, 14])

q = -1: bisect_right(xs, -1) - 1 = -1 -> clamp to seg 0 -> slope = (12-4)/(6-2) =  2.0 ->  4 + 2.0*(-1 - 2)  = -2.0
q =  6: bisect_right(xs,  6) - 1 =  1 -> exact hit xs[1] == 6                           ->  float(ys[1])      = 12.0
q = 18: bisect_right(xs, 18) - 1 =  2 -> clamp to seg 1 -> slope = (8-12)/(14-6) = -0.5 -> 12 + (-0.5)*(18-6) =  6.0

Complexity

Let n = len(knots) and q = len(queries).

  • Time: O((n + q) log n).
    • Sorting the n knot pairs by x-coordinate takes O(n log n) time, and splitting into xs and ys takes O(n) time.
    • Each of the q queries runs one bisect_right binary search over n elements in O(log n) time followed by O(1) floating-point arithmetic, totaling O(q log n).
  • Space: O(n + q).
    • Storing the sorted knots and the parallel xs and ys arrays uses O(n) memory, and the returned answers list holds q floats in O(q) memory.

Edge cases

  • Minimum knot count (n = 2): There is only one segment (seg_idx = 0), so interpolation, left extrapolation, and right extrapolation all lie on the same straight line.
  • Query directly on a knot (q == x_i, including x_min and x_max): knot_idx >= 0 and xs[knot_idx] == query_x catches every knot (even x_max, where knot_idx == n - 1) and returns float(ys[knot_idx]) with zero arithmetic rounding.
  • Extreme slopes and far extrapolation: Two knots 10^-6 apart vertically separated by 2 * 10^9 have a slope of 2 * 10^15; extrapolating 2 * 10^9 units away yields 4 * 10^24, well within IEEE-754 64-bit float range (up to ~1.8 * 10^308).
  • Unsorted or repeated queries: Queries are processed sequentially in input order, so duplicate queries and arbitrary ordering return matching positions in answers.
  • Integer inputs: Python's / performs true floating-point division, and float(ys[knot_idx]) ensures exact-knot hits return float values as well.

Common mistakes

  • Forgetting to sort knots first: Input points arrive in arbitrary order (as in Example 2); running bisect_right on unsorted x values produces garbage indices.
  • Forgetting to clamp knot_idx == -1: In Python, xs[-1] does not raise IndexError — it silently reads the last element of xs, causing left extrapolation to connect the last knot to the first knot!
  • Off-by-one when query_x >= xs[-1]: When query_x > xs[-1], bisect_right(xs, query_x) - 1 returns n - 1; failing to clamp down to n - 2 makes xs[seg_idx + 1] crash with IndexError.
  • Using numpy.interp directly: numpy.interp performs constant clamping outside [x_min, x_max] (returning [8.0, 4.0] on Example 2 instead of [6.0, -2.0]).
  • Extrapolating using (x_min, y_min) and (x_max, y_max): Left extrapolation uses only the two leftmost knots (0, 1), and right extrapolation uses only the two rightmost knots (n - 2, n - 1).
  • Sorting queries in place without tracking original indices: answers[j] must correspond to queries[j] in the original input order.

Alternative approaches

  • Offline two-pointer sweep (O(n log n + q log q)): Pair each query with its original index (query_x, j), sort both the knots and the indexed queries, and advance a single segment pointer seg_idx from left to right across [0, n - 2]. This avoids binary search entirely while writing each result back into answers[j].
  • Vectorized NumPy (O((n + q) log n) in C): After sorting xs and ys as NumPy arrays, compute seg = np.clip(np.searchsorted(xs, queries, side="right") - 1, 0, len(xs) - 2) and evaluate ys[seg] + (ys[seg + 1] - ys[seg]) / (xs[seg + 1] - xs[seg]) * (queries - xs[seg]) across all 100,000 queries in a few milliseconds.

Follow-up questions

  • How would you adapt the data structure if new knots are inserted and old knots are deleted online between queries? Store (x, y) knots in a balanced binary search tree or skip list (ordered search structures that keep keys sorted while supporting insert, delete, and predecessor/successor lookup in O(log n) time), such as SortedDict from sortedcontainers in Python or std::map in C++. Using bisect.insort on a plain Python list locates the position in O(log n), yet shifting trailing elements still costs O(n) per update.
  • When knots lie close together at large coordinates near 10^9, why can floating-point division lose accuracy and how can you compute exact results? Near 10^9, consecutive IEEE-754 64-bit floats sit roughly 2^-23 ≈ 1.19 * 10^-7 apart, so subtracting two knots only 10^-6 apart loses 5–7% relative precision in (x_1 - x_0) from binary rounding alone, which magnifies slope error when extrapolating far away. Because every input has at most 6 decimal places and |v| <= 10^9, scaling by round(v * 10**6) converts every coordinate into an exact integer bounded by 10^15 < 2^53, letting fractions.Fraction evaluate each line with zero intermediate rounding.
  • If downstream consumers differentiate L(x) and cannot tolerate slope jumps at the knots, what interpolation method would you switch to? Piecewise linear functions are continuous, yet their first derivative jumps discontinuously at every interior knot, producing spikes when differentiating curves. Switching to a cubic spline (piecewise cubic polynomials fitted so value, first derivative, and second derivative agree at every knot) yields smooth derivatives, while monotone cubic interpolation such as PCHIP (Piecewise Cubic Hermite Interpolating Polynomial, which constrains knot slopes so segments never overshoot monotone data) preserves C^1 smoothness without introducing artificial oscillations.

Follow-up questions

Similar questions

More Two Sigma interview questions

All 55 Two Sigma questions →