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
nstops numbered from0ton-1 - An array
distancewheredistance[i]represents the distance between stopiand stop(i+1) % n - A
startstop and adestinationstop
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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code