Distance Between Bus Stops — LeetCode 1184 Python Solution

EasyArray
Problem
#1184
Reading time
2 min

The problem

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.

Example

Input
distance = [1,2,3,4], start = 0, destination = 1
Output
1
Explanation
Distance between 0 and 1 is 1 or 9, minimum is 1.

Python solution

Python
class Solution:
    def distanceBetweenBusStops(
        self, distance: List[int], start: int, destination: int
    ) -> int:
        s = sum(distance)
        t, n = 0, len(distance)
        while start != destination:
            t += distance[start]
            start = (start + 1) % n
        return min(t, s - t)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array \textit{distance}
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1184. Distance Between Bus Stops?
LeetCode 1184. Distance Between Bus Stops is rated Easy on LeetCode.
What is the time complexity of LeetCode 1184. Distance Between Bus Stops?
The Python solution on this page runs in O(n), where n is the length of the array \textit{distance}.
What is the space complexity of LeetCode 1184. Distance Between Bus Stops?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1184. Distance Between Bus Stops cover?
LeetCode 1184. Distance Between Bus Stops is tagged Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview