Shortest Total Flight on a Circular Track of Stations
Arrays & HashingAuto-graded · 18 test casesLast updated
Sum the shortest arc distances between consecutive stops on a ring with weighted edges, using prefix sums for O(1) arc queries.
A courier network consists of n stations arranged in a closed loop and numbered 0 through n - 1. Each station is linked only to its two neighbors on the loop, and station n - 1 is linked to station 0. No other connections exist, so travel is only possible by moving from a station to an adjacent one.
You are given an integer list segments of length n. The value segments[i] is the length of the track between station i and station (i + 1) % n. Crossing a track costs its length, in either direction.
You are also given a list stops of station indices. A vehicle begins at stops[0] and must visit stops[1], stops[2], ..., in exactly that order, with no reordering and no skipping. For each consecutive pair of stops, the vehicle travels around the loop in whichever direction (increasing or decreasing index, wrapping around as needed) gives the smaller total length. If both directions have the same length, the cost is that common length. If the two stops are the same station, the cost of that leg is 0.
Return the total distance travelled over all legs. If stops has only one element, the answer is 0.
Implement the function so that it returns this total as an integer.
Constraints
2 <= n <= 10^51 <= segments[i] <= 10^41 <= len(stops) <= 10^50 <= stops[j] <= n - 1- Consecutive entries in
stopsmay be equal. - The total can exceed 32-bit range.
Examples
Example 1
Input: min_total_loop_travel([1, 2, 3, 4], [0, 2, 3])
Output: 6
Example 2
Input: min_total_loop_travel([1, 2, 3, 4], [1, 3])
Output: 5
Example 3
Input: min_total_loop_travel([4, 4, 4], [0, 1, 1, 0])
Output: 8
Hints
Hint 1
Each leg is independent, so the answer is the sum of the best cost for every consecutive pair of stops.
Hint 2
Between two stations there are exactly two routes, and together they cover the whole loop once. If one has length d, the other has length total - d.
Hint 3
Build a prefix-sum array of the segments so any forward arc length is available in O(1). Handle the case where the start index is larger than the end index by using the complement.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The stops must be visited in a fixed order, and the direction chosen on one leg does not affect any other leg. So the answer is the sum, over consecutive pairs of stops, of the shortest distance between them on the ring.
Between two stations on a ring there are only two sensible routes: one going toward higher indices and one going toward lower indices. They use disjoint sets of segments and together use every segment exactly once. So if the forward route has length f and the full loop has length total, the backward route has length total - f, and the leg costs min(f, total - f).
To get f quickly, build a prefix array where prefix[i] is the distance from station 0 to station i going forward, and prefix[n] is total.
- If
a <= b, the forward distance isprefix[b] - prefix[a]. - If
a > b, the forward route wraps around. The forward distance frombtoaisprefix[a] - prefix[b], so the forward distance fromatobistotal - (prefix[a] - prefix[b]).
Why it is correct
- Any route that reverses direction or circles more than needed only adds positive length, so only the two arcs matter.
- The two arcs partition the loop, so one is the complement of the other.
- When
a == b, the forward distance is0, so the leg costs0with no special case. - Ties are harmless since
minreturns the shared value. - With a single stop there are no legs, so the result is
0.
Complexity
Time is O(n + m) for n segments and m stops: O(n) to build the prefix sums and O(1) per leg. Space is O(n) for the prefix array. A naive walk around the ring for each leg would be O(n * m), which is too slow at the maximum sizes.
Reference solution
from typing import List
def min_total_loop_travel(segments: List[int], stops: List[int]) -> int:
n = len(segments)
prefix = [0] * (n + 1)
for i, length in enumerate(segments):
prefix[i + 1] = prefix[i] + length
total = prefix[n]
answer = 0
for j in range(len(stops) - 1):
a, b = stops[j], stops[j + 1]
if a <= b:
forward = prefix[b] - prefix[a]
else:
forward = total - (prefix[a] - prefix[b])
answer += min(forward, total - forward)
return answer