File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # 141. Linked List Cycle
3
+
4
+ use two pointers, Floyd's Tortoise and Hare algorithm
5
+
6
+ > Tortoise and Hare algorithm
7
+ >- slow pointer moves one step at a time
8
+ >- fast pointer moves two steps at a time
9
+ >- if there is a cycle, slow and fast will meet at some point
10
+ >- if there is no cycle, fast will reach the end of the list
11
+
12
+ ## Time Complexity: O(n)
13
+ In the worst case, we need to traverse the entire list to determine if there is a cycle.
14
+
15
+ ## Space Complexity: O(1)
16
+ no extra space is used, only the two pointers.
17
+ '''
18
+ class Solution :
19
+ def hasCycle (self , head : Optional [ListNode ]) -> bool :
20
+ if not head or not head .next :
21
+ return False
22
+
23
+ slow = head
24
+ fast = head
25
+
26
+ while fast and fast .next :
27
+ slow = slow .next
28
+ fast = fast .next .next
29
+
30
+ if slow == fast :
31
+ return True
32
+
33
+ return False
You can’t perform that action at this time.
0 commit comments