Evaluate a Piecewise Linear Curve From Shuffled Sample Points
Heaps, Sorting & SearchAuto-graded · 20 test casesLast updated
Build a piecewise linear function from unordered sample points and evaluate it at one query, extending the end segments outward, using sorting and binary search.
You are given n sample points of an unknown curve. The i-th point is (xs_in[i], ys_in[i]), and the points come in no particular order. Implement a function that evaluates the piecewise linear curve through these points at a single query position query_x. Do not use any interpolation library.
Definition of the curve
- Order the points by their x-coordinate, keeping each x paired with its own y.
- Between two neighbouring points in that order, the curve is the straight line segment joining them.
- If
query_xis smaller than the smallest x, continue the line through the two points with the smallest x to the left. - If
query_xis larger than the largest x, continue the line through the two points with the largest x to the right. - If
query_xis exactly equal to one of the sample x-coordinates, return the y-value stored for that point.
Return the value of the curve at query_x.
Input
n: the number of sample points.xs_in: a list ofnx-coordinates (unsorted).ys_in: a list ofny-coordinates, whereys_in[i]belongs toxs_in[i].query_x: the position to evaluate.
Output
A single float: the curve's value at query_x. An answer within 1e-9 absolute or relative error is accepted.
Constraints
2 <= n <= 200000len(xs_in) == len(ys_in) == n- Every
xs_in[i],ys_in[i], andquery_xis finite with absolute value at most10^6. - All x-coordinates are distinct, and after sorting, adjacent x-values differ by at least
10^-6. - After the sort, the lookup of the segment should take logarithmic time.
Examples
Example 1
Input: evaluate_piecewise_linear(3, [2, 0, 1], [4, 0, 1], 1.5)
Output: 2.5
Example 2
Input: evaluate_piecewise_linear(3, [2, 0, 1], [4, 0, 1], -1)
Output: -1
Hints
Hint 1
If you sort the x list and the y list separately, the pairs are broken. Sort the pairs together by x.
Hint 2
After sorting, check first whether query_x equals a stored x exactly; if so, return the matching y without any arithmetic.
Hint 3
For a query inside the range, a binary search finds the segment whose left x is the last one below query_x. For a query outside the range, clamp to the first segment or the last segment (indices 0 and n-2).
Hint 4
Use y0 + (query_x - x0) * (y1 - y0) / (x1 - x0) on the chosen segment; this same formula also handles extrapolation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Sort the points as (x, y) pairs so every y stays attached to its x, then split them into sorted arrays xs and ys. The query falls into one of these cases:
- Exact match.
bisect_left(xs, query_x)gives the first index with value>= query_x. If that value equalsquery_x, return the storedysvalue directly, which avoids any rounding. - Left of the range. Use segment index
0(the two smallest x values). - Right of the range. Use segment index
n - 2(the two largest x values). - Inside the range.
bisect_right(xs, query_x) - 1is the last index whose x is strictly belowquery_x; call iti. Thenxs[i] < query_x < xs[i+1].
On the chosen segment (x0, y0)–(x1, y1), return y0 + (query_x - x0) * (y1 - y0) / (x1 - x0). Extrapolation is the same formula with query_x outside [x0, x1].
Why it is correct
- Sorting pairs preserves the point-to-value association, and since the x values are distinct, the order is fully determined by x.
- The exact-match check handles all knot hits, including the smallest and largest, before the range checks.
- In the interior case,
query_x < xs[-1]guaranteesi + 1 <= n - 1, so the segment exists and brackets the query. - Clamping to
0andn - 2matches the rule of using the two outermost points for extrapolation. Whenn = 2, both clamps give the single segment. - The denominator
x1 - x0is at least1e-6, so there is no division by zero, and the magnitudes stay far below the double-precision limit.
Complexity
- Time: O(n log n) for the sort, O(n) to split the arrays, and O(log n) for the binary searches.
- Space: O(n).
Reference solution
from bisect import bisect_left, bisect_right
from typing import List
def evaluate_piecewise_linear(n: int, xs_in: List[float], ys_in: List[float], query_x: float) -> float:
pts = sorted(zip(xs_in, ys_in))
xs = [p[0] for p in pts]
ys = [p[1] for p in pts]
pos = bisect_left(xs, query_x)
if pos < n and xs[pos] == query_x:
return ys[pos]
if query_x < xs[0]:
i = 0
elif query_x > xs[-1]:
i = n - 2
else:
i = bisect_right(xs, query_x) - 1
x0, y0 = xs[i], ys[i]
x1, y1 = xs[i + 1], ys[i + 1]
return y0 + (query_x - x0) * (y1 - y0) / (x1 - x0)