The Distance Between Bus Stops coding problem involves a circular bus route with stops. You are given an array of distances where distance[i] represents the distance between stop i and stop (i + 1) % n. Given a starting stop and a destination stop, you need to find the shortest distance between them. Since the route is circular, you can travel either clockwise or counter-clockwise.
Google asks this question to test basic array logic and the ability to handle circular structures. It evaluations whether you can correctly identify the two possible paths in a circle and compare them. It’s a test of Array interview patterns and "complementary" thinking—realizing that the sum of the two path distances must equal the total circumference of the circle.
This problem uses Linear Iteration and the Sum Property.
start to destination.totalDistance - clockwiseDistance.Distances: [1, 2, 3, 4], Start: 0, Destination: 2.
total - path shortcut.start > destination by simply swapping them.Circular problems are often simpler than they appear. If you can calculate the distance for a "slice" of the circle, the rest of the circle is always the total minus that slice. This trick saves you from writing tricky modulo-based loops.