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. Ifxequalsx_i,L(x_i) = y_i; ifx_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, soL(4) = 4 + 2.0 * (4 - 2) = 8.0. x = 6lands directly on the middle knot(6, 12), returning12.0.- Between
(6, 12)and(14, 8)the slope is(8 - 12) / (14 - 6) = -0.5, soL(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,0001 <= len(queries) <= 100,000-10^9 <= x_i, y_i, queries[j] <= 10^9, each given with at most6digits after the decimal point- All knot
x-coordinatesx_iare 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
Understand the curve and extrapolation rule
We are given
n >= 2unsorted 2D pointsknots[i] = [x_i, y_i]with distinctx-coordinates, plus a list ofqueries. Once we sort the knots from smallestxto largestx, connecting each adjacent pair with a straight line segment defines a piecewise linear functionL(x)across[x_min, x_max].Outside
[x_min, x_max],L(x)continues along the outermost line segments (linear extrapolation): - Forx < x_min, follow the straight line passing through the two leftmost sorted knots(x_0, y_0)and(x_1, y_1). - Forx > 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.Why scanning per query is too slow
A straightforward brute-force approach sorts
knotsonce and then, for each queryq, loops through alln - 1segments to locate which[x_i, x_{i+1}]containsq. Withn = 100,000knots andq = 100,000queries,n * qreaches10^10operations — 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 whereqfalls in at mostceil(log2(n)) <= 17comparisons). Sorting once takesO(n log n)and answering allqqueries takesO(q log n), meeting the expectedO((n + q) log n)runtime.Unify interpolation and extrapolation with a clamped segment index
Notice that
nsorted knots definen - 1line segments, numbered0, 1, ..., n - 2, where segmenticonnects knotito knoti + 1. Every possible query — whether inside or outside[x_min, x_max]— lies on the line of one of thosen - 1segments: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 satisfyx <= query_x. Subtracting1givesknot_idx, the index of the rightmost knot at or to the left ofquery_x(or-1whenquery_x < x_0). Clampingknot_idxinto[0, n - 2]viamin(max(knot_idx, 0), n - 2)automatically routes left extrapolation to segment0, right extrapolation to segmentn - 2, and interior points to their enclosing segment — all with one point-slope formula!Sort the knots once and split `xs` and `ys`
Calling
sorted(knots)sorts[x, y]pairs byxfirst without mutating the caller's list (and since allxvalues are distinct,ynever breaks ties). Splitting the sorted points into two flat listsxsandysletsbisect_rightsearchxsdirectly 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, ysEvaluate 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 (includingx_max, whereknot_idx == n - 1), returningfloat(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: withoutmax(knot_idx, 0),knot_idx == -1would silently readxs[-1](the last knot!) instead of raising an error, and withoutmin(..., len(xs) - 2),seg_idx + 1would raiseIndexErrorwhenquery_x > x_max.Finally,
interpolateloops overqueriesin 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 answersTrace 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.0Notice 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).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
nknot pairs byx-coordinate takesO(n log n)time, and splitting intoxsandystakesO(n)time. - Each of the
qqueries runs onebisect_rightbinary search overnelements inO(log n)time followed byO(1)floating-point arithmetic, totalingO(q log n).
- Sorting the
- Space:
O(n + q).- Storing the sorted knots and the parallel
xsandysarrays usesO(n)memory, and the returnedanswerslist holdsqfloats inO(q)memory.
- Storing the sorted knots and the parallel
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, includingx_minandx_max):knot_idx >= 0 and xs[knot_idx] == query_xcatches every knot (evenx_max, whereknot_idx == n - 1) and returnsfloat(ys[knot_idx])with zero arithmetic rounding. - Extreme slopes and far extrapolation: Two knots
10^-6apart vertically separated by2 * 10^9have a slope of2 * 10^15; extrapolating2 * 10^9units away yields4 * 10^24, well within IEEE-754 64-bitfloatrange (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, andfloat(ys[knot_idx])ensures exact-knot hits returnfloatvalues as well.
Common mistakes
- Forgetting to sort
knotsfirst: Input points arrive in arbitrary order (as in Example 2); runningbisect_righton unsortedxvalues produces garbage indices. - Forgetting to clamp
knot_idx == -1: In Python,xs[-1]does not raiseIndexError— it silently reads the last element ofxs, causing left extrapolation to connect the last knot to the first knot! - Off-by-one when
query_x >= xs[-1]: Whenquery_x > xs[-1],bisect_right(xs, query_x) - 1returnsn - 1; failing to clamp down ton - 2makesxs[seg_idx + 1]crash withIndexError. - Using
numpy.interpdirectly:numpy.interpperforms 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
queriesin place without tracking original indices:answers[j]must correspond toqueries[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 pointerseg_idxfrom left to right across[0, n - 2]. This avoids binary search entirely while writing each result back intoanswers[j]. - Vectorized NumPy (
O((n + q) log n)in C): After sortingxsandysas NumPy arrays, computeseg = np.clip(np.searchsorted(xs, queries, side="right") - 1, 0, len(xs) - 2)and evaluateys[seg] + (ys[seg + 1] - ys[seg]) / (xs[seg + 1] - xs[seg]) * (queries - xs[seg])across all100,000queries 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 inO(log n)time), such asSortedDictfromsortedcontainersin Python orstd::mapin C++. Usingbisect.insorton a plain Pythonlistlocates the position inO(log n), yet shifting trailing elements still costsO(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 roughly2^-23 ≈ 1.19 * 10^-7apart, so subtracting two knots only10^-6apart 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 byround(v * 10**6)converts every coordinate into an exact integer bounded by10^15 < 2^53, lettingfractions.Fractionevaluate 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^1smoothness without introducing artificial oscillations.
Follow-up questions
- How would you adapt the data structure if new knots are inserted and old knots are deleted online between queries?
- 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?
- If downstream consumers differentiate L(x) and cannot tolerate slope jumps at the knots, what interpolation method would you switch to?
Similar questions
- Column-Wise Addition of Decimal Strings
- Balanced Two-Task Staffing for Minimum Hours
- One-Way Fleet Capacity Scaling Under Load
- Highest Multi-Hop Currency Conversion
- Polyline Interpolation and Extrapolation
- Unique Island Shapes Under Translation
More Two Sigma interview questions
- OLS Subset Selection for NYC Daily Temperatures Medium
- Regional Temperature Modeling and Streaming Regression Medium
- Polyline Interpolation and Extrapolation Medium Pro
- Scalable Quantitative Portfolio Optimization Platform Medium Pro
- Bounded Piecewise Linear Curve Evaluation Medium Pro
- Price-Time Limit Order Book Engine Medium Pro
- Deterministic Frequency-Tree String Codec Hard Pro
- Price-Time Priority Order Book Engine Medium Pro
- Column-Wise Addition of Decimal Strings Hard Pro
- Top Borough-Hour Taxi Speed Medians Medium Pro