Read a Value Off a Connected Line-Segment Graph
Heaps, Sorting & SearchAuto-graded · 24 test casesLast updated
Evaluate a piecewise linear curve at a query coordinate by locating the right segment with binary search and interpolating, returning None outside the curve's domain.
A curve is drawn by joining a list of 2D vertices in order with straight segments. The vertices are sorted by strictly increasing x-coordinate, so the curve is the graph of a function of x.
Write a function that returns the height of this curve at a given horizontal position.
Rules
Let the vertices be (x_0, y_0), (x_1, y_1), ..., (x_{n-1}, y_{n-1}), and let query_x be the position to evaluate.
-
If
query_xis exactly equal to somex_i, returny_i. -
If
x_i < query_x < x_{i+1}for somei, return the value on the straight segment joining those two vertices:y_i + (y_{i+1} - y_i) * (query_x - x_i) / (x_{i+1} - x_i) -
If
query_x < x_0orquery_x > x_{n-1}, the curve is not defined there. ReturnNone. Do not extend the end segments.
Input
vertices: a list ofnpairs[x, y], sorted by strictly increasingx.query_x: the horizontal position to evaluate.
Output
The height of the curve at query_x as a number, or None if query_x is outside [x_0, x_{n-1}].
Constraints
n >= 2x_0 < x_1 < ... < x_{n-1}(strictly increasing, so no segment is vertical)- Coordinates and
query_xmay be negative, zero, integer or fractional. - Segments may be flat, rising or falling.
Examples
Example 1
Input: interpolate_on_polyline([[0, 0], [10, 10]], 5)
Output: 5
Example 2
Input: interpolate_on_polyline([[0, 0], [2, 4], [5, 1]], 3)
Output: 3
Example 3
Input: interpolate_on_polyline([[0, 0], [1, 5], [3, 2]], 1)
Output: 5
Example 4
Input: interpolate_on_polyline([[0, 0], [1, 5]], -1)
Output: None
Hints
Hint 1
Because the x-values are strictly increasing, the domain splits into consecutive intervals. First decide whether query_x lies inside the overall range at all.
Hint 2
Binary search for the last vertex whose x is less than or equal to query_x. With Python's bisect module, bisect_right on the list of x-values minus one gives that index.
Hint 3
Be careful when query_x equals the final vertex's x: there is no next vertex to interpolate toward, so return that vertex's y directly. Also return the stored y on any exact vertex hit.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Since the x-coordinates are strictly increasing, they split the domain [x_0, x_{n-1}] into consecutive intervals, and each point in the domain belongs to a well-defined segment.
- Range check. If
query_xis smaller than the first x or larger than the last x, returnNone. - Find the segment. Collect the x-values into a list and use
bisect_right(xs, query_x) - 1. This gives the indexiof the last vertex withx_i <= query_x. Usingbisect_righthandles both an exact hit and a strictly interior point with one rule. - Handle the right end. If
iis the last index, thenquery_xequals the final x (anything larger was rejected), so return that vertex's y. This also avoids reading past the end of the list. - Exact vertex. If
query_x == x_i, returny_iunchanged. - Interpolate. Otherwise
x_i < query_x < x_{i+1}, and the line formula gives the answer. The denominatorx_{i+1} - x_iis positive because the x-values are strictly increasing.
Why it is correct
After the range check, x_0 <= query_x <= x_{n-1}, so the found index i is at least 0. For any i < n - 1 we have x_i <= query_x < x_{i+1}, so the point lies on exactly the segment we interpolate on, and the formula is the equation of the line through its two endpoints. The final vertex is the only case with no following segment, and it is handled separately. Flat segments give y_i since y_{i+1} - y_i = 0.
Complexity
- Time: O(n) to build the list of x-values, plus O(log n) for the binary search. A single call is O(n). If many queries are made on the same vertices, build
xsonce and each query costs O(log n). - Space: O(n) for the x-value list.
Reference solution
from bisect import bisect_right
from typing import List, Optional
def interpolate_on_polyline(vertices: List[List[float]], query_x: float) -> Optional[float]:
xs = [v[0] for v in vertices]
# Outside the domain of the curve.
if query_x < xs[0] or query_x > xs[-1]:
return None
# Index of the last vertex with x <= query_x.
i = bisect_right(xs, query_x) - 1
# query_x equals the last vertex's x: no segment starts there.
if i == len(vertices) - 1:
return vertices[i][1]
x1, y1 = vertices[i]
x2, y2 = vertices[i + 1]
# Exact hit on a vertex: return the stored value.
if query_x == x1:
return y1
return y1 + (y2 - y1) * (query_x - x1) / (x2 - x1)