Distance Between Bus Stops — LeetCode 1184 Python Solution
EasyArray
- Problem
- #1184
- Reading time
- 2 min
- Source
- leetcode.com
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array \textit{distance} |
| Space | O(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.