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
Circular Bus Route: Find Shortest Distance01231234StartEndTwo possible paths - choose the shorter one
Understanding the Visualization
1
Input
Circular bus route with distances [1,2,3,4] between consecutive stops
2
Process
Calculate distance in both clockwise and counterclockwise directions
3
Output
Return the minimum distance between start and destination
Key Takeaway
🎯 Key Insight: On a circle, there are exactly two paths between any two points - calculate both and take the minimum
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