EasyNo. 1184
Distance Between Bus Stops — LeetCode 1184 Python Solution
- Topics
- Array
- 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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0057 | Insert Interval | Medium |
| 0228 | Summary Ranges | Easy |
| 0485 | Max Consecutive Ones | Easy |
| 0665 | Non-decreasing Array | Medium |
| 0674 | Longest Continuous Increasing Subsequence | Easy |
| 0699 | Falling Squares | Hard |
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.