forked from SamirPaulb/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path457_Circular_Array_Loop.py
29 lines (26 loc) · 1.12 KB
/
457_Circular_Array_Loop.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
for i in range(len(nums)):
if nums[i] == 0:
continue
# if slow and fast pointers collide, then there exists a loop
slow = i
fast = self.index(nums, slow)
while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0:
if slow == fast and fast != self.index(nums, fast):
return True
elif slow == fast and fast == self.index(nums, fast):
break
slow = self.index(nums, slow)
fast = self.index(nums, self.index(nums, fast))
# set path to all 0s since it doesn't work
runner = i
value = nums[runner]
while nums[runner] * value > 0:
temp = self.index(nums, runner)
nums[runner] = 0
runner = temp
return False
def index(self, nums, index):
length = len(nums)
return (index + nums[index] + length) % length