Skip to the code
cf.
+10 XP

#182 Find a Frame by Timestamp

easy

A video player keeps the timestamps of its decoded frames in timestamps, in milliseconds, sorted ascending with no repeats. Frames arrive at a nearly steady rate, so the timestamps are spread fairly evenly.

Write findFrame(timestamps, target) that returns the index of the frame with timestamp target, or -1 if there is none. Use the even spacing: guess the position from the value, as interpolation search does.

Example 1

Input: timestamps = [0,40,80,120,160,200,240], target = 160
Output: 4

With frames every 40 ms, the first guess lands right on index 4.

Example 2

Input: timestamps = [0,40,80,120,160,200,240], target = 100
Output: -1

No frame has timestamp 100.

Constraints

  • 0 <= timestamps.length <= 100000
  • Sorted ascending, no repeats.
  • 0 <= timestamps[i], target <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).