Magicsheet logo

Distance Between Bus Stops

Easy
25%
Updated 8/1/2025

Asked by 1 Company

Topics

Distance Between Bus Stops

What is this problem about?

The Distance Between Bus Stops coding problem involves a circular bus route with nn 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.

Why is this asked in interviews?

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.

Algorithmic pattern used

This problem uses Linear Iteration and the Sum Property.

  1. Calculate the total distance of all stops (the full circle).
  2. Calculate the distance traveling in one direction (e.g., clockwise) from start to destination.
  3. The distance in the other direction is simply totalDistance - clockwiseDistance.
  4. The answer is the minimum of these two.

Example explanation

Distances: [1, 2, 3, 4], Start: 0, Destination: 2.

  1. Clockwise: Stop 0 \to 1 (dist 1) + Stop 1 \to 2 (dist 2) = 3.
  2. Total Distance: 1+2+3+4=101 + 2 + 3 + 4 = 10.
  3. Counter-Clockwise: 103=710 - 3 = 7.
  4. Shortest: min(3,7)=3\min(3, 7) = 3.

Common mistakes candidates make

  • Incorrect Directional Logic: Trying to write complex loops for both directions instead of using the total - path shortcut.
  • Start/End Confusion: Failing to handle cases where start > destination by simply swapping them.
  • Off-by-one: Miscalculating the indices in the distance array (e.g., including the distance from the destination to the next stop).

Interview preparation tip

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.

Similar Questions