KatInterview

Evaluate a Broken-Line Curve at a Query Position

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

Last updated

Sort scattered points by x, then find the y on the connecting line at a query x, interpolating inside the range and extending the end segments outside it.

You are given a list of 2D points, each written as [x, y]. The list is in arbitrary order, and no two points share the same x-value.

Imagine ordering the points by increasing x and joining each pair of neighbours with a straight segment. The result is a continuous broken-line curve (a polyline) defined over the x-axis.

Write a function that, given a query position query_x, returns the y-value of this curve at that position. The rules are:

  • If query_x equals the x-value of one of the points, return that point's y-value.
  • If query_x lies strictly between the x-values of two neighbouring points (after ordering), return the y-value of the straight segment joining those two points at query_x.
  • If query_x is less than every x-value, extend the straight line through the two points with the smallest x-values and evaluate it at query_x.
  • If query_x is greater than every x-value, extend the straight line through the two points with the largest x-values and evaluate it at query_x.

Use true (floating-point) division when computing slopes. Do not truncate to integers.

Constraints

  • There are at least 2 points.
  • All x-values among the points are distinct.
  • Each point is a pair [x, y] of numbers (integers or floats, possibly negative).
  • query_x is a number and may lie inside or outside the range of the point x-values.
  • The input list should not be modified.

Examples

Example 1

Input: curve_value([[0, 0], [10, 20], [20, 10]], 5)

Output: 10

Hints

Hint 1

Once the points are ordered by x, the curve is fully determined by neighbouring pairs. Think about how to locate the pair that surrounds the query.

Hint 2

A binary search on the sorted x-values gives an insertion index. Check for an exact match first, then decide between left extension (index 0), right extension (index n), or a bracketing pair.

Hint 3

Interpolation and extrapolation share one formula: y1 + (q - x1) * (y2 - y1) / (x2 - x1). Only the choice of the two points differs.