09 Sept 2026Go / Python / TypeScriptEasy

Distance Between Bus Stops

Find the shorter travel distance between two stops on a circular route.

Sum the clockwise segment between the ordered stops and compare it with the total route distance minus that segment.

complexity

O(n) time and O(1) space.

solution files

  • Go distance-between-bus-stops/solution.go
  • Python distance-between-bus-stops/solution.py
  • TypeScript distance-between-bus-stops/solution.ts

Solution files

Godistance-between-bus-stops/solution.go
package main

func distanceBetweenBusStops(distance []int, start int, destination int) int {
	if start > destination {
		start, destination = destination, start
	}
	total, direct := 0, 0
	for stop, value := range distance {
		total += value
		if stop >= start && stop < destination {
			direct += value
		}
	}
	if direct < total-direct {
		return direct
	}
	return total - direct
}
Pythondistance-between-bus-stops/solution.py
class Solution:
    def distanceBetweenBusStops(self, distance: list[int], start: int, destination: int) -> int:
        if start > destination: start, destination = destination, start
        direct = sum(distance[start:destination]); return min(direct, sum(distance) - direct)
TypeScriptdistance-between-bus-stops/solution.ts
function distanceBetweenBusStops(distance: number[], start: number, destination: number): number {
  if (start > destination) [start, destination] = [destination, start];
  const total = distance.reduce((sum, value) => sum + value, class="syntax-number">0); let direct = class="syntax-number">0; for (let stop = start; stop < destination; stop += class="syntax-number">1) direct += distance[stop]; return Math.min(direct, total - direct);
}