Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Interpolated Car Position

MediumPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Interpolated Car Position. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

ChicagoTrading receives timestamped car-position samples as two parallel arrays. Given sorted sample times, corresponding positions, and a query time, return the car's estimated position at that time.

Use linear interpolation between the two samples surrounding the query. If the query is before the first sample, extrapolate from the first two samples. If it is after the final sample, extrapolate from the final two samples. If the query exactly matches a recorded timestamp, return the recorded position. Round the result to the nearest integer; when the value is exactly halfway between integers, round away from zero.

Formal Specification

Implement estimate_position(times, positions, query_time).

  • times is a strictly increasing list of integers.
  • positions is a list of integers with the same length as times.
  • query_time is an integer.
  • Return one integer position.

The solution must use binary search to identify the relevant pair of samples. Avoid floating-point precision errors when computing the rounded result.

Constraints

  • 2 <= len(times) == len(positions) <= 10^6
  • times[i] < times[i + 1] for every valid i
  • -10^9 <= times[i], positions[i], query_time <= 10^9
  • Return an integer rounded to the nearest whole position
  • Halfway values must be rounded away from zero

Function Signature

def estimate_position(times, positions, query_time):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output