Evaluate a Piecewise Linear Function
Two SigmaData Scientist · Online AssessmentLast updated
This question tests the ability to efficiently search through a sorted collection of coordinates and apply linear interpolation to compute values for a continuous piecewise function.
Problem Statement
You are given a list of 2D points points representing a piecewise linear function. The list contains n points (x_i, y_i) where x_0 < x_1 < ... < x_{n-1}. Your task is to implement a function that evaluates this function at any given point x.
If x falls exactly on one of the x_i coordinates, return the corresponding y_i. If x lies between x_i and x_{i+1}, return the result of the linear interpolation between the two points. If x is outside the range [x_0, x_{n-1}], return null (or the equivalent None/Empty value).
Function Signature
def evaluate_piecewise(points, x):
Constraints
points: A list of tuples(x, y)sorted byx.n(number of points):2 <= n <= 10^5.x: A floating-point number.- Time complexity should be better than
O(n).
Examples
Example 1:
- Input:
points = [(0, 0), (2, 4), (4, 4)],x = 1 - Output:
2.0 - Explanation: Since 1 is between 0 and 2, the line segment between
(0,0)and(2,4)has a slope of 2.y = 0 + 2 * (1 - 0) = 2.
Example 2:
- Input:
points = [(0, 0), (2, 4), (4, 4)],x = 5 - Output:
null
Edge Cases
xis exactly the first or last point.xis significantly outside the bounds.- The function is horizontal (slope = 0) between two points.
Hints
Hint 1
Since the x-coordinates are sorted, consider using binary search to identify the interval [x_i, x_{i+1}] that contains the target x.
Hint 2
The linear interpolation formula for a point x between (x0, y0) and (x1, y1) is y = y0 + (y1 - y0) * ((x - x0) / (x1 - x0)).
Hint 3
Use the `bisect_right` function from Python's `bisect` module to quickly find the insertion point of x in the list of sorted x-values.
Follow-up questions
- How would your implementation change if the x-coordinates were not guaranteed to be sorted?
- If you had to perform millions of queries on the same set of points, what pre-processing step could you take to improve performance?
- How would you handle potential precision issues when working with floating-point x values?
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.