algoadvance

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.

Clarifying Questions

  1. Is the bus route circular? Yes, the bus route is circular, meaning that the end of the route connects back to the beginning.

  2. 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.

  3. 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.

Strategy

  1. Understanding the Route: Since the route is circular, there are two possible paths between start and destination:
    • Clockwise Path: This path follows the sequence from start to destination directly.
    • Counterclockwise Path: This path goes from start to destination by going the other way around the circle.
  2. Calculating Distances:
    • Calculate the distance for both the clockwise and counterclockwise paths.
    • To find the shortest path, we take the minimum of both distances.
  3. Steps to Implement Solution:
    • If start is greater than destination, swap them to simplify the calculations (always move from smaller index to larger index).
    • Calculate the clockwise distance by summing distance from start to destination.
    • Calculate the counterclockwise distance by summing the remainder of distance array (from destination to end and then from start to destination).
    • Return the minimum of these two distances.

Code

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

This approach efficiently calculates the shortest distance between two bus stops on a circular route.

Try our interview co-pilot at AlgoAdvance.com