Peak Rolling Kilometer Speed Across Five-Second Splits

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

A telemetry sensor logs the integer number of meters traveled during each consecutive 5-second split of an athletic session, producing an array distances where distances[i] is the distance covered in split i. Compute the peak average speed achieved over any rolling one-kilometer (1000-meter) window.

Implement the function:

def fastest_rolling_km_speed(distances: list[int]) -> float:

Apply the following definitions:

  • Any contiguous slice of splits [l, r] (0 <= l <= r < len(distances)) spans 5 * (r - l + 1) seconds and covers distances[l] + distances[l + 1] + ... + distances[r] meters.
  • For each ending index r, the rolling one-kilometer window ending at r is the shortest contiguous slice [l, r] (meaning the largest start index l <= r) whose total distance is at least 1000 meters. If distances[0] + ... + distances[r] < 1000, index r has no rolling window.
  • A rolling window's average speed (in meters per second) equals its full meter total divided by 5 * (r - l + 1) — splits are never prorated or interpolated when the sum exceeds 1000 meters.
  • Return the largest average speed among all valid rolling windows, or -1.0 if the sum across the entire distances array is strictly below 1000 meters.
  • Any return value within 1e-6 absolute or relative tolerance of the exact speed is accepted.

Examples

Example 1

Input: distances = [450, 350, 250, 150, 600, 450]
Output: 105.0

Ending indices 0 (450 m) and 1 (800 m) do not yet reach 1000 meters. For r = 2, 3, 4, 5, the shortest >= 1000-meter windows are [0, 2] (1050 m in 15 s = 70.0 m/s), [0, 3] (1200 m in 20 s = 60.0 m/s), [2, 4] (1000 m in 15 s ≈ 66.667 m/s), and [4, 5] (1050 m in 10 s = 105.0 m/s). The peak rolling speed is 105.0.

Example 2

Input: distances = [310, 290, 180, 215]
Output: -1.0

All four splits sum to 995 meters, which never reaches 1000 meters, so no rolling window exists.

Example 3

Input: distances = [0, 550, 650, 0, 450]
Output: 120.0

At r = 2, [1, 2] already covers 550 + 650 = 1200 meters in 10 seconds (120.0 m/s); split 0 (0 m) is excluded because [1, 2] is shorter and still meets the 1000-meter threshold. The remaining rolling windows are [1, 3] (1200 m in 15 s = 80.0 m/s) and [2, 4] (1100 m in 15 s ≈ 73.333 m/s).

Constraints

  • 1 <= len(distances) <= 100000
  • 0 <= distances[i] <= 1000, with each entry an integer
  • sum(distances) <= 100000000
  • Whenever a valid rolling window exists, the exact result is strictly greater than 0.0 and at most 200.0 meters per second

Step-by-step walkthrough

  1. Understand what "rolling one-kilometer window" means

    Every entry distances[i] is the meters run during 5-second interval i. Before writing any code, read the problem's two core rules carefully—almost every bug on this question comes from misreading one of them:

    1. At most ONE candidate window per end r: For a fixed ending interval r, the rolling 1-km window is the shortest contiguous range [l, r] whose sum is >= 1000 meters (meaning the largest start index l that still reaches 1000). Longer windows ending at the same r are not rolling windows, even if one of them happens to have a higher average speed!
    2. Full distance counts (no interpolation): If [l, r] sums to 1050 meters across 3 intervals (15 seconds), its average speed is 1050 / 15 = 70.0 m/s—not 1000 / 15.

    Look at distances = [900, 99, 950] at end r = 2 to see Rule 1 in action:

    Index:        0      1      2
    Distances:  [900,   99,   950]
    
    Window [0, 2]:  900 + 99 + 950 = 1949m in 15s -> 129.93 m/s  (NOT the rolling window: too long!)
    Window [1, 2]:        99 + 950 = 1049m in 10s -> 104.90 m/s  (VALID rolling window for r = 2)
    Window [2, 2]:             950 =  950m in  5s -> under 1000m (too short)
    

    For r = 2, [1, 2] already covers at least 1000 meters and is shorter than [0, 2], so [1, 2] (104.9 m/s) is the only rolling window scored at r = 2. And if the entire workout totals less than 1000 meters, no r has a rolling window, so we return -1.0.

  2. Brute force: walk backward from every end interval

    The most direct way to find the shortest window ending at r is to start l at r and step backward (r, r - 1, r - 2, ...) until the running sum first hits 1000 meters:

    for each r from 0 to n - 1:
        walk l from r down to 0, adding distances[l]:
            as soon as meters >= 1000:
                score meters / (5 * (r - l + 1)) and stop walking!
    

    This finds the exact right window for every r, and our test suite uses it to cross-check small random runs. Why is it too slow here? Suppose distances has 99,999 zeros (or 1-meter strolls) followed by 1000. For almost every r, the inner loop walks all the way back to index 0, performing roughly n² / 2 ≈ 5 * 10^9 additions for n = 100,000.

  3. Key insight: the window's left edge never moves backward

    Because every distances[i] >= 0, watch what happens to the best start index l(r) when we move from r - 1 to r:

    Suppose for r - 1, the shortest >= 1000m window starts at l = 2:
      [  d0,   d1, | d2,   d3,   d4 |,  d5 ]
                   |<-- >= 1000m -->|
                     l(4) = 2         r-1=4
    
    Now include d5 >= 0 at r = 5:
      [  d0,   d1, | d2,   d3,   d4,   d5 | ]
                   |<---- still >= 1000m ->|
    

    Since [l(r - 1), r - 1] already had at least 1000 meters and distances[r] >= 0, [l(r - 1), r] is guaranteed to have at least 1000 meters too! That means for end r, we never need to look anywhere to the left of l(r - 1): l(r) >= l(r - 1) always.

    This turns the problem into an O(n) sliding window with two pointers left and right:

    1. Advance right by 1 and add distances[right] to window_meters.
    2. While dropping distances[left] would still leave window_meters - distances[left] >= 1000, subtract distances[left] and increment left.
  4. Why we shrink with `>=` and score only AFTER shrinking

    Two small details in that while loop are critical:

    1. Use >= 1000, not > 1000:
      • If window_meters - distances[left] == 1000, the shorter window [left + 1, right] still reaches 1000 meters, so we must drop left.
      • Even better, if distances[left] == 0 (a 0-meter pause at the left edge of a valid window), window_meters - 0 >= 1000 is true, so left automatically steps past leading zeros!
      • Could left ever run past right? Never: if left == right, then window_meters - distances[left] == 0, which is < 1000, so the loop stops immediately.
    2. Score once after the while loop, never inside it:
      • Standard "minimum-size subarray sum" templates often check answers inside while window_meters >= 1000:. Doing that here would score intermediate, non-shortest windows (like [0, 2] on [900, 99, 950]) before left finishes shrinking! Shrinking first and scoring [left, right] once afterward guarantees we only ever score the true rolling window for right.
  5. Code the sliding window

    INTERVAL_SECONDS = 5
    TARGET_METERS = 1000
    
    
    def fastest_rolling_km_speed(distances: list[int]) -> float:
        best_speed = -1.0
    
        # Sliding window [left..right]; window_meters stores sum(distances[left : right + 1])
        left = 0
        window_meters = 0
    
        for right in range(len(distances)):
            window_meters += distances[right]
    
            # Shrink from the left while the remaining window STILL covers at least 1000 meters.
            # Using '>=' also drops leading 0-meter intervals, and left never passes right because 0 < 1000.
            while window_meters - distances[left] >= TARGET_METERS:
                window_meters -= distances[left]
                left += 1
    
            # Score ONLY after shrinking finishes: only the single shortest >= 1000m window
            # ending at `right` counts as the rolling window for `right`.
            if window_meters >= TARGET_METERS:
                duration_seconds = INTERVAL_SECONDS * (right - left + 1)
                window_speed = window_meters / duration_seconds
                if window_speed > best_speed:
                    best_speed = window_speed
    
        return best_speed
    
  6. Trace Example 3 step by step

    Let's trace distances = [0, 550, 650, 0, 450]:

    right  add  before shrink     shrink steps (need rest >= 1000)      final [left, right]   speed
    ------------------------------------------------------------------------------------------------------
    0        0  [0..0] =    0m    none (0 - 0 < 1000)                   < 1000m (not scored)  best = -1.0
    1      550  [0..1] =  550m    none (550 - 0 < 1000)                 < 1000m (not scored)  best = -1.0
    2      650  [0..2] = 1200m    drop idx 0 (0m -> rest 1200 >= 1000)  [1, 2] = 1200m / 10s  120.0 m/s
                                  stop at idx 1 (1200 - 550 = 650)      -> new best = 120.0
    3        0  [1..3] = 1200m    stop at idx 1 (1200 - 550 = 650)      [1, 3] = 1200m / 15s   80.0 m/s
    4      450  [1..4] = 1650m    drop idx 1 (550m -> rest 1100 >= 1000)[2, 4] = 1100m / 15s   73.3 m/s
                                  stop at idx 2 (1100 - 650 = 450)
    

    Notice how at right = 2, the leading 0 at index 0 is cleanly dropped because 1200 - 0 >= 1000, leaving [1, 2] (1200 m in 10 s = 120.0 m/s). Across the whole run, best_speed finishes at 120.0.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    INTERVAL_SECONDS = 5
    TARGET_METERS = 1000
    
    
    def fastest_rolling_km_speed(distances: list[int]) -> float:
        best_speed = -1.0
    
        # Sliding window [left..right]; window_meters stores sum(distances[left : right + 1])
        left = 0
        window_meters = 0
    
        for right in range(len(distances)):
            window_meters += distances[right]
    
            # Shrink from the left while the remaining window STILL covers at least 1000 meters.
            # Using '>=' also drops leading 0-meter intervals, and left never passes right because 0 < 1000.
            while window_meters - distances[left] >= TARGET_METERS:
                window_meters -= distances[left]
                left += 1
    
            # Score ONLY after shrinking finishes: only the single shortest >= 1000m window
            # ending at `right` counts as the rolling window for `right`.
            if window_meters >= TARGET_METERS:
                duration_seconds = INTERVAL_SECONDS * (right - left + 1)
                window_speed = window_meters / duration_seconds
                if window_speed > best_speed:
                    best_speed = window_speed
    
        return best_speed
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of how a GPS running watch updates your live "current 1-km pace" every 5 seconds: each time a new 5-second split arrives at the front, the watch trims old splits off the back of its tail for as long as the remaining tail still totals at least 1000 meters, then divides that tail's actual meters by its duration. Because every split is non-negative (distances[i] >= 0), once an old split is trimmed off the back, you will never need it again for any future end point—adding new meters in the future only makes the tail longer, never forcing you to reach further into the past.

The naive approach starts fresh at every end index r and walks backward (r, r - 1, ...) until the sum hits 1000 meters. On a slow run or a long rest of 99,999 zeros followed by 1000, walking all the way back to index 0 from every r takes O(n²) operations (around 5 billion steps for n = 100,000) and times out.

Instead, we maintain a sliding window [left, right] (a contiguous subarray bounded by two indices that both move only from left to right, also called a two-pointer scan). Walk through Example 3, distances = [0, 550, 650, 0, 450]:

  1. right = 0 (0m) and right = 1 (0 + 550 = 550m): total is below 1000m, so nothing is trimmed and nothing is scored (best_speed stays -1.0).
  2. right = 2 (+650m -> 1200m): trimming distances[0] = 0 leaves 1200 >= 1000, so left moves to 1; trimming distances[1] = 550 would leave 650 < 1000, so we stop at [1, 2] (1200m / 10s = 120.0 m/s).
  3. right = 3 (+0m -> 1200m): cannot trim 550, so [1, 3] scores 1200m / 15s = 80.0 m/s.
  4. right = 4 (+450m -> 1650m): trimming distances[1] = 550 leaves 1100 >= 1000, advancing left to 2 and scoring [2, 4] at 1100m / 15s ≈ 73.33 m/s; the max remains 120.0.

Complexity

  • Time: O(n). The outer loop advances right across the n splits once, and across the entire run left increments at most n times without ever moving backward, so the inner while loop does amortized O(1) work per step (a constant average number of operations per split, at most 2n additions/subtractions in total).
  • Space: O(1). We only store scalar variables (best_speed, left, window_meters, duration_seconds, and window_speed), using zero extra arrays.

Edge cases

  • Total workout under 1000 meters (Example 2 [310, 290, 180, 215] or all zeros): window_meters >= 1000 never triggers, so best_speed stays at -1.0.
  • Single split of 1000 meters ([1000]): [0, 0] covers 1000m in 5s, giving the maximum possible 200.0 m/s; [999] returns -1.0.
  • Leading zeros ([0, 0, 500, 500]): Because the shrink test uses >= 1000 (1000 - 0 >= 1000), all leading 0-meter splits are dropped before scoring, whereas interior zeros ([500, 0, 500]) stay inside the window and add 5 seconds each.
  • Overshoot above 1000 meters ([999, 999]): [0, 1] is the shortest window reaching 1000m (999 < 1000), and its full 1998 meters count: 1998 / 10 = 199.8 m/s, not 1000 / 10.
  • Integer range: Total distance is at most 10^8, which fits comfortably inside standard 32-bit signed integers as well as Python's arbitrary-precision int.

Common mistakes

  • Scoring inside the while loop instead of after it: Copying the textbook "minimum-size subarray sum" loop (while window_meters >= 1000: best = max(...); window_meters -= distances[left]; left += 1) scores longer, non-rolling windows! On [900, 99, 950], that bug scores [0, 2] (1949 / 15 ≈ 129.9 m/s) even though the rolling window for r = 2 is [1, 2] (1049 / 10 = 104.9 m/s). Always finish shrinking first, then score once.
  • Maximizing over all subarrays of sum >= 1000: On [900, 100, 900], the whole array [0, 2] runs at 1900 / 15 ≈ 126.7 m/s, but [0, 2] is not the rolling window for r = 2 ([1, 2] already has 1000m and is shorter), so the true answer is 100.0 m/s.
  • Using strict > instead of >= when shrinking (window_meters - distances[left] > 1000): Fails to drop distances[left] when the remaining window has exactly 1000 meters, and fails to strip leading 0-meter splits!
  • Dividing 1000 instead of window_meters by duration_seconds: The rules count the entire distance of [left, right], without cutting intervals proportionally.
  • Returning 0.0 instead of -1.0 when no window reaches 1000 meters: Initializes best_speed to the wrong sentinel value.

Follow-up questions

  • What changes if a window must span an exact 1000-meter stretch by linearly interpolating within boundary splits? Under constant speed inside each 5-second split (linear interpolation, taking a proportional fraction of an interval's meters and duration), nudging any mid-split 1000-meter window toward the faster of its two end splits shrinks its duration until either its start or its end lands on a 5-second boundary. You can then run a forward two-pointer scan pinning the start to each boundary (interpolating the partial end split), run the identical scan on distances[::-1] to cover end-pinned windows, and divide 1000 by the shortest duration found in O(n) time.
  • How would you also report the start and end split indices of the winning rolling window? Keep two extra integers best_left, best_right = -1, -1 alongside best_speed, and update best_left, best_right = left, right inside if window_speed > best_speed:. Using strict > breaks ties in favor of the earliest rolling window (whereas >= would pick the latest); state your tie-breaking choice explicitly to the interviewer.
  • How could you maintain the rolling kilometer speed over an endless live stream of splits using bounded memory? Notice the algorithm only ever inspects splits inside the active window [left..right], so you can push incoming splits onto the right of a deque (a double-ended queue supporting O(1) appends on the right and O(1) pops from the left) and popleft() whenever window_meters - queue[0] >= 1000. To prevent a multi-hour rest stop of 0s from growing the deque unboundedly, merge consecutive zeros with run-length encoding (storing (meters, count) pairs instead of individual zeros): because [left + 1..right] sums to at most 999 meters, it contains at most 999 positive splits and at most 1000 zero runs, bounding memory to O(TARGET_METERS) (<= 2000 entries) forever!

Follow-up questions

Similar questions

More Optiver interview questions

All 76 Optiver questions →