File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def circularArrayLoop (self , nums : List [int ]) -> bool :
3
+ for i in range (len (nums )):
4
+ if nums [i ] == 0 :
5
+ continue
6
+
7
+ # if slow and fast pointers collide, then there exists a loop
8
+ slow = i
9
+ fast = self .index (nums , slow )
10
+ while nums [slow ] * nums [fast ] > 0 and nums [slow ] * nums [self .index (nums , fast )] > 0 :
11
+ if slow == fast and fast != self .index (nums , fast ):
12
+ return True
13
+ elif slow == fast and fast == self .index (nums , fast ):
14
+ break
15
+ slow = self .index (nums , slow )
16
+ fast = self .index (nums , self .index (nums , fast ))
17
+
18
+ # set path to all 0s since it doesn't work
19
+ runner = i
20
+ value = nums [runner ]
21
+ while nums [runner ] * value > 0 :
22
+ temp = self .index (nums , runner )
23
+ nums [runner ] = 0
24
+ runner = temp
25
+ return False
26
+
27
+ def index (self , nums , index ):
28
+ length = len (nums )
29
+ return (index + nums [index ] + length ) % length
You can’t perform that action at this time.
0 commit comments