Distance Between Bus Stops

easy array math simulation

Problem

A bus travels along a circular route. The array distance gives the distance between stop i and stop (i + 1) % n. Given a start and a destination stop, return the shortest distance the bus must travel — it may go clockwise or counterclockwise.

Inputdistance = [1, 2, 3, 4], start = 0, destination = 2
Output3
Clockwise from 0 to 2 covers 1 + 2 = 3. Counterclockwise covers 4 + 3 = 7. The minimum is 3.

def distance_between_bus_stops(distance, start, destination):
    if start > destination:
        start, destination = destination, start
    clockwise = sum(distance[start:destination])
    total = sum(distance)
    return min(clockwise, total - clockwise)
function distanceBetweenBusStops(distance, start, destination) {
  if (start > destination) [start, destination] = [destination, start];
  let clockwise = 0, total = 0;
  for (let i = 0; i < distance.length; i++) {
    total += distance[i];
    if (i >= start && i < destination) clockwise += distance[i];
  }
  return Math.min(clockwise, total - clockwise);
}
class Solution {
    public int distanceBetweenBusStops(int[] distance, int start, int destination) {
        if (start > destination) { int t = start; start = destination; destination = t; }
        int clockwise = 0, total = 0;
        for (int i = 0; i < distance.length; i++) {
            total += distance[i];
            if (i >= start && i < destination) clockwise += distance[i];
        }
        return Math.min(clockwise, total - clockwise);
    }
}
int distanceBetweenBusStops(vector<int>& distance, int start, int destination) {
    if (start > destination) swap(start, destination);
    int clockwise = 0, total = 0;
    for (int i = 0; i < (int)distance.size(); i++) {
        total += distance[i];
        if (i >= start && i < destination) clockwise += distance[i];
    }
    return min(clockwise, total - clockwise);
}
Time: O(n) Space: O(1)