Ctrl K

Shortest Way Around the Loop

Easy
A circular metro line has n stations numbered 0 to n − 1, and trains run in both directions. segments[i] is the length of the track between station i and station (i + 1) mod n. Return the length of the shortest trip from station start to station finish. If they are the same station, the answer is 0.
Example 1
segments=[3, 8, 2, 5], start=1, finish=3 → 8

Clockwise: 8 + 2 = 10; counterclockwise: 3 + 5 = 8. The answer is 8.

Example 2
segments=[6, 1, 4], start=2, finish=0 → 4

From station 2 to station 0 it is 4 along the direct segment, or 6 + 1 = 7 the other way.

Example 3
segments=[7, 7], start=1, finish=1 → 0
Constraints
  • 1 ≤ n = len(segments) ≤ 10⁴
  • 0 ≤ segments[i] ≤ 10⁴
  • 0 ≤ start, finish < n
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPair With a Target Sum EasySqueeze Repeats Out of a Sorted Array EasyDrop the Unwanted Value EasySlot on a Sorted Shelf EasyAdd One to a Digit Array Easy
loading Python…
Input
segments=[3, 8, 2, 5], start=1, finish=3
Expected
8

Run checks the first 3 tests in your browser. Submit checks all 71 tests on the server, hidden ones included.