KatInterview

Shortest Total Flight on a Circular Track of Stations

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingprefix-sumcircular-arraysimulation

Last 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^5
  • 1 <= segments[i] <= 10^4
  • 1 <= len(stops) <= 10^5
  • 0 <= stops[j] <= n - 1
  • Consecutive entries in stops may 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.