Distance Between Bus Stops - Problem

Imagine you're planning your commute on a circular bus route that connects several stops in a perfect loop. The bus operates in both directions - you can go clockwise or counterclockwise to reach your destination!

You're given:

  • A circular bus route with n stops numbered from 0 to n-1
  • An array distance where distance[i] represents the distance between stop i and stop (i+1) % n
  • A start stop and a destination stop

Your goal is to find the shortest distance between the start and destination stops. Since it's a circular route, you can travel in either direction, so you need to calculate both paths and return the minimum distance.

Example: If you have stops [0,1,2,3] in a circle with distances [1,2,3,4], going from stop 0 to stop 2 could be done clockwise (1+2=3) or counterclockwise (4+3=7), so the answer would be 3.

Input & Output

example_1.py โ€” Basic circular route
$ Input: distance = [1,2,3,4], start = 0, destination = 1
โ€บ Output: 1
๐Ÿ’ก Note: Going clockwise from stop 0 to stop 1 takes distance[0] = 1. Going counterclockwise would be 2+3+4 = 9. So the minimum is 1.
example_2.py โ€” Longer clockwise path
$ 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. Minimum is 3.
example_3.py โ€” Equal distances
$ Input: distance = [1,2,3,4], start = 0, destination = 3
โ€บ Output: 4
๐Ÿ’ก Note: Clockwise: 1 + 2 + 3 = 6. Counterclockwise: 4. The shorter path is counterclockwise with distance 4.

Constraints

  • 1 โ‰ค n โ‰ค 104
  • 0 โ‰ค start, destination < n
  • 0 โ‰ค distance[i] โ‰ค 104
  • start != destination

Visualization

Tap to expand
START0Stop 1DEST2Stop 3Distance: 1Distance: 2Distance: 3Distance: 4Path CalculationsClockwise: 0โ†’1โ†’2Sum = 1 + 2 = 3Counterclockwise: 0โ†’3โ†’2Sum = 4 + 3 = 7
Understanding the Visualization
1
Set Up the Circle
Visualize all bus stops arranged in a perfect circle with distances marked between adjacent stops
2
Calculate Clockwise
Sum up distances going clockwise from start to destination
3
Calculate Counterclockwise
Use total perimeter minus clockwise to get counterclockwise distance
4
Choose Optimal Path
Return the minimum distance between the two possible routes
Key Takeaway
๐ŸŽฏ Key Insight: On a circular route, there are exactly two paths between any two stops. Calculate one path by direct summation, then use the fact that both paths together equal the total perimeter to find the other path instantly!
Asked in
Amazon 15 Google 8 Meta 5 Microsoft 3
28.5K Views
Medium Frequency
~8 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