Evaluate piecewise linear function at x
Two SigmaData Scientist · Online AssessmentLast updated
This question evaluates competency in numerical interpolation and handling of piecewise linear functions, including locating the correct segment in a sorted sequence of points and managing out-of-range inputs.
You are given a polyline defined by n 2D points ((x_i, y_i)). Connecting consecutive points with straight line segments forms a piecewise linear function.
Task
Given a target value x, return the corresponding function value y(x):
- If
xequals somex_i, returny_i. - If
xlies strictly betweenx_iandx_{i+1}, linearly interpolate on the segment between ((x_i, y_i)) and ((x_{i+1}, y_{i+1})): [ y(x)=y_i + (y_{i+1}-y_i)\cdot\frac{x-x_i}{x_{i+1}-x_i} ] - If
x < x_0orx > x_{n-1}, returnnull(or a sentinel) because the function is undefined outside the polyline.
Input
points: list ofnpairs(x, y)x: target x-coordinate
Assumptions / Constraints
n >= 2- Points are given sorted by strictly increasing
x(i.e.,x0 < x1 < ... < x(n-1)).
Output
- A numeric value
y(x)(float), ornullif out of range.
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.