KatInterview

Read a Value Off a Connected Line-Segment Graph

Heaps, Sorting & SearchAuto-graded · 24 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchinterpolationarrays

Last 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_x is exactly equal to some x_i, return y_i.

  • If x_i < query_x < x_{i+1} for some i, 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_0 or query_x > x_{n-1}, the curve is not defined there. Return None. Do not extend the end segments.

Input

  • vertices: a list of n pairs [x, y], sorted by strictly increasing x.
  • 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 >= 2
  • x_0 < x_1 < ... < x_{n-1} (strictly increasing, so no segment is vertical)
  • Coordinates and query_x may 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.