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
30
| class Solution:
def circularArrayLoop(self, nums: List[int]) -> bool:
n = len(nums)
def next_index(i):
return (i + nums[i] + n) % n
for i in range(n):
if nums[i] == 0:
continue
slow, fast = i, next_index(i)
while nums[i] * nums[fast] > 0 and nums[i] * nums[next_index(fast)] > 0:
if slow == fast:
# Check if the loop has length > 1
if slow == next_index(slow):
break
return True
slow = next_index(slow)
fast = next_index(next_index(fast))
# Marking visited indices with 0 to avoid reprocessing
slow = i
while nums[i] * nums[slow] > 0:
next_slow = next_index(slow)
nums[slow] = 0
slow = next_slow
return False
|