Distance Between Bus Stops
Let’s break down the solution into simpler steps.
We have two possible paths to go from the start
to the destination
:
- Moving clockwise from
start
to destination
. - Moving counterclockwise from
start
to destination
.
We’ll calculate the distance for both paths and return the minimum distance.
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| class Solution:
def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
# If start is greater than destination, swap them to make sure we move forward in the list
if start > destination:
start, destination = destination, start
# Calculate the clockwise distance from start to destination
clockwise_distance = 0
for i in range(start, destination):
clockwise_distance += distance[i]
# Calculate the total distance in the circle
total_distance = sum(distance)
# Calculate the counterclockwise distance using total distance minus clockwise distance
counterclockwise_distance = total_distance - clockwise_distance
# Return the minimum of both distances
return min(clockwise_distance, counterclockwise_distance)
|
In the code, we first make sure that start
is less than destination
by swapping them if needed. Then, we calculate the distance in both directions and return the minimum.
This implementation is clear and easy to follow, and its time complexity is O(n), where n is the number of bus stops.