KatInterview

Evaluate a Piecewise Linear Curve From Shuffled Sample Points

Heaps, Sorting & SearchAuto-graded · 20 test cases
MediumAuto-gradedHeaps, Sorting & Searchbinary-searchsortinginterpolation

Last 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

  1. Order the points by their x-coordinate, keeping each x paired with its own y.
  2. Between two neighbouring points in that order, the curve is the straight line segment joining them.
  3. If query_x is smaller than the smallest x, continue the line through the two points with the smallest x to the left.
  4. If query_x is larger than the largest x, continue the line through the two points with the largest x to the right.
  5. If query_x is 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 of n x-coordinates (unsorted).
  • ys_in: a list of n y-coordinates, where ys_in[i] belongs to xs_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 <= 200000
  • len(xs_in) == len(ys_in) == n
  • Every xs_in[i], ys_in[i], and query_x is finite with absolute value at most 10^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.