Distance Between Bus Stops

EasyArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A circular bus route has n stops numbered 0 to n - 1. The array distance describes the route: distance[i] is the length of the road between stop i and stop (i + 1) % n. Buses run in both directions. Given start and destination, return the length of the shorter of the two ways around the circle between them. If start == destination, the answer is 0.

Examples

Input: distance = [1,2,3,4], start = 0, destination = 1
Output: 1
Going clockwise costs 1; counter-clockwise costs 2 + 3 + 4 = 9.
Input: distance = [1,2,3,4], start = 0, destination = 2
Output: 3
Clockwise costs 1 + 2 = 3; the other way costs 3 + 4 = 7.
Input: distance = [1,2,3,4], start = 0, destination = 3
Output: 4
Clockwise costs 6; counter-clockwise uses only the road of length 4.

Constraints

  • 1 <= n <= 10^4
  • distance.length == n
  • 0 <= start, destination < n
  • 0 <= distance[i] <= 10^4

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems