Skip to content

Commit 29ac8d2

Browse files
authored
Create 1184-dist_between_bus_stops.py
1 parent 60907ea commit 29ac8d2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

1184-dist_between_bus_stops.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
https://leetcode.com/problems/distance-between-bus-stops/submissions/
3+
4+
Strat: calculate the distance when going clockwise and then counterclockwise. Then
5+
return the smaller of the two.
6+
7+
Stats: O(n) time, O(1) space
8+
Runtime: 52 ms, faster than 9.41% of Python online submissions for Distance Between Bus Stops.
9+
Memory Usage: 13.2 MB, less than 67.06% of Python online submissions for Distance Between Bus Stops.
10+
11+
Awesome solution: https://leetcode.com/problems/distance-between-bus-stops/discuss/481987/Python-O(-n-)-sol-by-shortest-path.-90%2B-With-explanation
12+
"""
13+
class Solution(object):
14+
def distanceBetweenBusStops(self, distance, start, destination):
15+
"""
16+
:type distance: List[int]
17+
:type start: int
18+
:type destination: int
19+
:rtype: int
20+
"""
21+
#ensure start is less than destination
22+
if start > destination:
23+
start, destination = destination, start
24+
25+
clockwise = 0
26+
for i in range(start, destination):
27+
clockwise += distance[i]
28+
29+
counter_clockwise = 0
30+
i = destination
31+
while i != start:
32+
counter_clockwise += distance[i % len(distance)]
33+
i = (i + 1) % len(distance)
34+
35+
return min(clockwise, counter_clockwise)

0 commit comments

Comments
 (0)