Implement Piecewise Linear Interpolation and Extrapolation
CitadelData Scientist · Technical ScreenLast updated
Implement piecewise linear interpolation from unsorted knots, including exact-knot behavior and endpoint extrapolation. Practice paired sorting, binary search, and numerical edge cases.
Given n points (x_knots[i], y_knots[i]) in arbitrary order and a query x_input, implement piecewise linear interpolation without using an interpolation library:
linear_interpolate(
n: int,
x_knots: List[float],
y_knots: List[float],
x_input: float
) -> float
Sort the knots by x. If x_input lies between two adjacent knots, return the value on the line segment connecting them. If it lies outside the knot range, extrapolate using the nearest end segment.
Constraints
2 <= n <= 200_000len(x_knots) == len(y_knots) == n- Every
x_knots[i],y_knots[i], andx_inputis finite and has absolute value at most10^6. - All
x_knotsare distinct. After sorting, every adjacent pair differs by at least10^-6. - An answer within
1e-9absolute or relative error is accepted.
Clarifications
- If
x_inputequals a knot exactly, return that knot'syvalue. - Left extrapolation uses the two smallest
xvalues; right extrapolation uses the two largest. - The function handles one query, but the search should still be logarithmic after sorting.
- The magnitude and separation bounds keep the slope, extrapolation product, and returned value finite in the IEEE 754 double precision used by all four console languages.
Examples
Input: n = 3, x_knots = [2, 0, 1], y_knots = [4, 0, 1], x_input = 1.5
Output: 2.5
Input: n = 3, x_knots = [2, 0, 1], y_knots = [4, 0, 1], x_input = -1
Output: -1
Evaluation Focus
- Preservation of each
(x, y)pair during sorting. - Correct segment choice at knots and outside the range.
- The linear interpolation formula and floating-point behavior.
- (O(n\log n)) preprocessing and (O(\log n)) lookup.
Extension
How would you preprocess once to answer one million query values efficiently?
Hints
Hint 1
Locate the bracketing segment: After sorting paired knots, use binary search for the first knot whose x-coordinate is not less than the query, then clamp the segment index at the two ends.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.