#1184
Easy Algorithms Distance between bus stops
Array
55.2% acceptance
Feb 25, 2026
814
95
A bus has n stops numbered from 0 to n - 1 that form a circle. We know the distance between all pairs of neighboring stops where distance[i] is the distance between the stops number i and (i + 1) % n.
The bus goes along both directions i.e. clockwise and counterclockwise.
Return the shortest distance between the given start and destination stops.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn distance_between_bus_stops(distance: Vec<i32>, start: i32, destination: i32) -> i32 {
let _n = distance.len();
let (mut s, mut d) = (start as usize, destination as usize);
if s > d { std::mem::swap(&mut s, &mut d); }
let clockwise: i32 = distance[s..d].iter().sum();
let total: i32 = distance.iter().sum();
clockwise.min(total - clockwise)
}
}