EasyNo. 1184

Distance Between Bus Stops — LeetCode 1184 Python Solution

Topics
Array
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

PythonSolution
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

Time
O(n)where n is the length of the array distance
Space · auxiliary
O(1)

Related problems

Related problems
No.ProblemDifficulty
0057Insert IntervalMedium
0228Summary RangesEasy
0485Max Consecutive OnesEasy
0665Non-decreasing ArrayMedium
0674Longest Continuous Increasing SubsequenceEasy
0699Falling SquaresHard

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.

Free to download. Check it runs on your machine, then pick a plan.