You are given an integer array distance where distance[i] represents the distance between the i-th and (i+1)-th bus stops. You are also given two integers start and destination both in the range [0, distance.length - 1].
Return the shortest distance between the bus stops start and destination.
Is the bus route circular? Yes, the bus route is circular, meaning that the end of the route connects back to the beginning.
Can start and destination be the same?
If start is equal to destination, the distance would be zero since you do not need to travel.
Do we need to consider edge cases with minimum and maximum lengths of distance?
Yes, we should handle edge cases where the length of the distance array can have minimum and maximum lengths as allowed by constraints.
start and destination:
start to destination directly.start to destination by going the other way around the circle.start is greater than destination, swap them to simplify the calculations (always move from smaller index to larger index).distance from start to destination.distance array (from destination to end and then from start to destination).Here’s the implementation of the above strategy in Python:
def distanceBetweenBusStops(distance, start, destination):
if start > destination:
start, destination = destination, start
# Calculate clockwise distance
clockwise_distance = sum(distance[start:destination])
# Calculate counterclockwise distance
counterclockwise_distance = sum(distance) - clockwise_distance
return min(clockwise_distance, counterclockwise_distance)
# Example Usage
distance = [1, 2, 3, 4]
start = 0
destination = 2
print(distanceBetweenBusStops(distance, start, destination)) # Output: 3
start = 2
destination = 0
print(distanceBetweenBusStops(distance, start, destination)) # Output: 7
Time Complexity: (O(n)), where (n) is the length of the distance array. This is because in the worst case, we might need to sum up all the elements in the distance array for the counterclockwise calculation.
Space Complexity: (O(1)), as we are using only a constant amount of extra space for variables.
This approach efficiently calculates the shortest distance between two bus stops on a circular route.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?