Compute Piecewise Linear Interpolation
Two SigmaData Scientist · Online AssessmentLast updated
This question evaluates skills in algorithm design and numerical interpolation, including sorting and searching among 2D points, handling boundary cases for extrapolation, and computing linear interpolation accurately and efficiently.
You are given an unsorted list of distinct 2D points (x_i, y_i). When the points are sorted by x_i, connecting adjacent points forms a polyline.
Given a query value x, return the corresponding y value on this polyline:
- If
xexactly matches an existing point's x-coordinate, return that point's y-coordinate. - If
xlies between two adjacent points, use linear interpolation. - If
xis smaller than the minimum x-coordinate, extrapolate using the first two points after sorting. - If
xis larger than the maximum x-coordinate, extrapolate using the last two points after sorting.
Design an efficient algorithm. You may assume there are at least two points and all x-coordinates are distinct.
Example:
points = [(0, 0), (10, 20), (20, 10)]
x = 5
output = 10
Explanation: x = 5 lies halfway between (0, 0) and (10, 20), so the interpolated y-value is 10.
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.