Evaluate piecewise linear function at x
Company: Two Sigma
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Take-home Project
Quick Answer: This question evaluates competency in numerical interpolation and handling of piecewise linear functions, including locating the correct segment in a sorted sequence of points and managing out-of-range inputs.
Constraints
- 2 <= len(points) <= 100000
- points[i][0] < points[i+1][0] for all valid i
- Each coordinate and the target x is an integer or floating-point number in the range [-10^9, 10^9]
Examples
Input: ([(0, 0), (2, 4), (5, 1)], 2)
Expected Output: 4.0
Explanation: The target x matches an existing point (2, 4), so the answer is 4.0.
Input: ([(0, 0), (10, 10)], 5)
Expected Output: 5.0
Explanation: The target lies halfway between x=0 and x=10 on a line from y=0 to y=10, so the interpolated value is 5.0.
Input: ([(-3, -6), (1, 2), (4, 2)], -1)
Expected Output: -2.0
Explanation: The target lies between (-3, -6) and (1, 2). Interpolating gives -6 + (2 - (-6)) * ((-1 - (-3)) / (1 - (-3))) = -2.0.
Input: ([(-3, -6), (1, 2), (4, 2)], -3)
Expected Output: -6.0
Explanation: The target x matches the first point exactly, so return its y-value.
Input: ([(-3, -6), (1, 2), (4, 2)], 5)
Expected Output: None
Explanation: The target x is greater than the last x-coordinate, so the function is undefined there.
Hints
- Because the x-coordinates are sorted, you can use binary search to find the segment containing the target x.
- Handle the easy cases first: out-of-range values and exact matches to an existing point.