Distance Between Bus Stops - Problem

A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.

The bus goes along both directions i.e. clockwise and counterclockwise. Return the shortest distance between the given start and destination stops.

Input & Output

Example 1 — Basic Circle
$ Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
💡 Note: Clockwise: distance[0] = 1. Counterclockwise: distance[3] + distance[2] + distance[1] = 4 + 3 + 2 = 9. Return min(1, 9) = 1.
Example 2 — Opposite Direction Better
$ Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
💡 Note: Clockwise: distance[0] + distance[1] = 1 + 2 = 3. Counterclockwise: distance[3] + distance[2] = 4 + 3 = 7. Return min(3, 7) = 3.
Example 3 — Equal Distances
$ Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
💡 Note: Clockwise: 1 + 2 + 3 = 6. Counterclockwise: 4. Return min(6, 4) = 4.

Constraints

  • 1 ≤ n ≤ 104
  • distance.length == n
  • 0 ≤ start, destination < n
  • 0 ≤ distance[i] ≤ 104

Visualization

Tap to expand
Distance Between Bus Stops INPUT 0 1 2 3 1 2 3 4 START DEST distance = [1, 2, 3, 4] start = 0 destination = 1 n = 4 stops (circular) ALGORITHM STEPS 1 Calculate Total Distance Sum all: 1+2+3+4 = 10 2 Clockwise Distance Sum from start to dest 3 Counter-clockwise total - clockwise = other 4 Return Minimum min(clockwise, counter) Calculation: total = 1+2+3+4 = 10 clockwise(0-->1) = 1 counter = 10-1 = 9 min(1, 9) = 1 FINAL RESULT 0 1 2 3 Clockwise: 1 (shorter) Counter: 9 (longer) OUTPUT 1 OK - Shortest path found! Key Insight: In a circular bus route, there are exactly TWO paths between any two stops. Instead of calculating both separately, compute one path and subtract from total to get the other. Time: O(n) single pass | Space: O(1) constant TutorialsPoint - Distance Between Bus Stops | Optimized - Single Pass with Total
Asked in
Amazon 15 Microsoft 8
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen