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)) spans5 * (r - l + 1)seconds and coversdistances[l] + distances[l + 1] + ... + distances[r]meters. - For each ending index
r, the rolling one-kilometer window ending atris the shortest contiguous slice[l, r](meaning the largest start indexl <= r) whose total distance is at least1000meters. Ifdistances[0] + ... + distances[r] < 1000, indexrhas 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 exceeds1000meters. - Return the largest average speed among all valid rolling windows, or
-1.0if the sum across the entiredistancesarray is strictly below1000meters. - Any return value within
1e-6absolute 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) <= 1000000 <= distances[i] <= 1000, with each entry an integersum(distances) <= 100000000- Whenever a valid rolling window exists, the exact result is strictly greater than
0.0and at most200.0meters per second
Step-by-step walkthrough
Understand what "rolling one-kilometer window" means
Every entry
distances[i]is the meters run during 5-second intervali. Before writing any code, read the problem's two core rules carefully—almost every bug on this question comes from misreading one of them:- At most ONE candidate window per end
r: For a fixed ending intervalr, the rolling 1-km window is the shortest contiguous range[l, r]whose sum is>= 1000meters (meaning the largest start indexlthat still reaches1000). Longer windows ending at the samerare not rolling windows, even if one of them happens to have a higher average speed! - Full distance counts (no interpolation): If
[l, r]sums to1050meters across3intervals (15seconds), its average speed is1050 / 15 = 70.0m/s—not1000 / 15.
Look at
distances = [900, 99, 950]at endr = 2to 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 least1000meters and is shorter than[0, 2], so[1, 2](104.9m/s) is the only rolling window scored atr = 2. And if the entire workout totals less than1000meters, norhas a rolling window, so we return-1.0.- At most ONE candidate window per end
Brute force: walk backward from every end interval
The most direct way to find the shortest window ending at
ris to startlatrand step backward (r, r - 1, r - 2, ...) until the running sum first hits1000meters: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? Supposedistanceshas99,999zeros (or1-meter strolls) followed by1000. For almost everyr, the inner loop walks all the way back to index0, performing roughlyn² / 2 ≈ 5 * 10^9additions forn = 100,000.Key insight: the window's left edge never moves backward
Because every
distances[i] >= 0, watch what happens to the best start indexl(r)when we move fromr - 1tor: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 least1000meters anddistances[r] >= 0,[l(r - 1), r]is guaranteed to have at least1000meters too! That means for endr, we never need to look anywhere to the left ofl(r - 1):l(r) >= l(r - 1)always.This turns the problem into an
O(n)sliding window with two pointersleftandright:- Advance
rightby1and adddistances[right]towindow_meters. - While dropping
distances[left]would still leavewindow_meters - distances[left] >= 1000, subtractdistances[left]and incrementleft.
- Advance
Why we shrink with `>=` and score only AFTER shrinking
Two small details in that
whileloop are critical:- Use
>= 1000, not> 1000:- If
window_meters - distances[left] == 1000, the shorter window[left + 1, right]still reaches1000meters, so we must dropleft. - Even better, if
distances[left] == 0(a0-meter pause at the left edge of a valid window),window_meters - 0 >= 1000is true, soleftautomatically steps past leading zeros! - Could
leftever run pastright? Never: ifleft == right, thenwindow_meters - distances[left] == 0, which is< 1000, so the loop stops immediately.
- If
- Score once after the
whileloop, 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]) beforeleftfinishes shrinking! Shrinking first and scoring[left, right]once afterward guarantees we only ever score the true rolling window forright.
- Standard "minimum-size subarray sum" templates often check answers inside
- Use
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_speedTrace 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 leading0at index0is cleanly dropped because1200 - 0 >= 1000, leaving[1, 2](1200m in10s =120.0m/s). Across the whole run,best_speedfinishes at120.0.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]:
right = 0(0m) andright = 1(0 + 550 = 550m): total is below1000m, so nothing is trimmed and nothing is scored (best_speedstays-1.0).right = 2(+650m -> 1200m): trimmingdistances[0] = 0leaves1200 >= 1000, soleftmoves to1; trimmingdistances[1] = 550would leave650 < 1000, so we stop at[1, 2](1200m / 10s = 120.0m/s).right = 3(+0m -> 1200m): cannot trim550, so[1, 3]scores1200m / 15s = 80.0m/s.right = 4(+450m -> 1650m): trimmingdistances[1] = 550leaves1100 >= 1000, advancingleftto2and scoring[2, 4]at1100m / 15s ≈ 73.33m/s; the max remains120.0.
Complexity
- Time: O(n). The outer loop advances
rightacross thensplits once, and across the entire runleftincrements at mostntimes without ever moving backward, so the innerwhileloop does amortized O(1) work per step (a constant average number of operations per split, at most2nadditions/subtractions in total). - Space: O(1). We only store scalar variables (
best_speed,left,window_meters,duration_seconds, andwindow_speed), using zero extra arrays.
Edge cases
- Total workout under
1000meters (Example 2[310, 290, 180, 215]or all zeros):window_meters >= 1000never triggers, sobest_speedstays at-1.0. - Single split of
1000meters ([1000]):[0, 0]covers1000min5s, giving the maximum possible200.0m/s;[999]returns-1.0. - Leading zeros (
[0, 0, 500, 500]): Because the shrink test uses>= 1000(1000 - 0 >= 1000), all leading0-meter splits are dropped before scoring, whereas interior zeros ([500, 0, 500]) stay inside the window and add5seconds each. - Overshoot above
1000meters ([999, 999]):[0, 1]is the shortest window reaching1000m(999 < 1000), and its full1998meters count:1998 / 10 = 199.8m/s, not1000 / 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-precisionint.
Common mistakes
- Scoring inside the
whileloop 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.9m/s) even though the rolling window forr = 2is[1, 2](1049 / 10 = 104.9m/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 at1900 / 15 ≈ 126.7m/s, but[0, 2]is not the rolling window forr = 2([1, 2]already has1000mand is shorter), so the true answer is100.0m/s. - Using strict
>instead of>=when shrinking (window_meters - distances[left] > 1000): Fails to dropdistances[left]when the remaining window has exactly1000meters, and fails to strip leading0-meter splits! - Dividing
1000instead ofwindow_metersbyduration_seconds: The rules count the entire distance of[left, right], without cutting intervals proportionally. - Returning
0.0instead of-1.0when no window reaches1000meters: Initializesbest_speedto 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 ondistances[::-1]to cover end-pinned windows, and divide1000by the shortest duration found inO(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, -1alongsidebest_speed, and updatebest_left, best_right = left, rightinsideif 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 supportingO(1)appends on the right andO(1)pops from the left) andpopleft()wheneverwindow_meters - queue[0] >= 1000. To prevent a multi-hour rest stop of0s 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 most999meters, it contains at most999positive splits and at most1000zero runs, bounding memory toO(TARGET_METERS)(<= 2000entries) forever!
Follow-up questions
- What changes if a window must span an exact 1000-meter stretch by linearly interpolating within boundary splits?
- How would you also report the start and end split indices of the winning rolling window?
- How could you maintain the rolling kilometer speed over an endless live stream of splits using bounded memory?
Similar questions
- Validate Edge Pairs and Serialize Binary Tree
- Elapsed Days Across Extended Gregorian Dates
- Sequential Freight Dispatch Across Scheduled Aircraft
- Core Data Structure Trade-Offs, Invariants, and Workload Selection
- Verifying Functional Equivalence Between Integer Array Routines
- Counting Valid Buy-and-Sell Trade Sequences
More Optiver interview questions
- Thermal Throttling Simulator for Multicore Processors Hard
- Probability, Betting Edge, and Arrival Metrics Medium
- Negative Final Price Probability Medium Pro
- Counting Distinct Strings with Duplicate Characters Easy Pro
- Stochastic Process Expectations and Ruin Easy Pro
- Subsequence Sum DP, Indexed Heap Scheduler, and Heuristic k-Selection Medium Pro
- Cognitive Task-Switching Tactics and Two-Week Training Regimen Medium Pro
- Orbital Relay Broadcast and Callback Simulator Medium Pro
- Topic-Filtered News Subscription Engine Hard Pro
- Intraday Mean-Reversion Strategy Backtest Hard Pro