KatInterview

Quickest Way to Cover a Set Distance From Per-Interval Odometer Data

Arrays & HashingAuto-graded · 21 test cases
MediumAuto-gradedArrays & Hashingprefix-sumsbinary-searchinterpolation

Last updated

Find the top average speed over any time window covering exactly a target distance, given piecewise-constant speeds. Tests prefix sums, interpolation and binary search.

A survey drone logs how far it travels in equal time slots. Entry slots[i] is the number of meters flown during slot i, and every slot lasts slot_seconds seconds. Slot i therefore occupies the time interval [i * slot_seconds, (i + 1) * slot_seconds].

Within a single slot the drone moves at a constant speed. Once t seconds of slot i have passed, it has flown slots[i] * t / slot_seconds meters of that slot's distance.

You want the drone's fastest window for a fixed distance. Choose a continuous time window [a, b] in which the drone flies exactly goal meters in total. The window's average speed is goal / (b - a). Return the largest average speed achievable by any such window.

Rules

  • a and b may be any real numbers with 0 <= a < b <= len(slots) * slot_seconds. A window may begin or end in the middle of a slot.
  • Slots with 0 meters (the drone hovers) still contribute their full duration to any window that contains them.
  • A window may lie entirely inside one slot, provided that slot alone covers at least goal meters.
  • Results within 1e-6 relative error are accepted.

Constraints

  • 1 <= len(slots) <= 10^5
  • 0 <= slots[i] <= 10^5
  • 1 <= goal <= sum(slots)
  • slot_seconds is a positive number.
  • Cumulative distances can exceed 2^31, so use 64-bit integers in fixed-width languages.
  • Aim for O(n log n) or better.

Examples

Example 1

Input: fastest_window_speed([100, 100, 100, 100, 100], 10, 500)

Output: 10

Example 2

Input: fastest_window_speed([50, 300, 0, 250, 150], 10, 500)

Output: 17.857142857142858

Example 3

Input: fastest_window_speed([20, 900, 40], 10, 500)

Output: 90

Hints

Hint 1

Build prefix sums of the distances. The total distance flown by time t is a non-decreasing piecewise-linear function, and the best window is the one with the shortest duration.

Hint 2

For a fixed start time, the duration of the best window changes linearly while neither endpoint crosses a slot boundary. So an optimal window can be found with its start or its end exactly on a slot boundary.

Hint 3

For each boundary, binary search the prefix sums for the matching other end and interpolate inside the slot. Use the earliest time for the end and the latest time for the start, so hovering slots are never counted needlessly.