Skip to content

Commit 1fcdcfc

Browse files
committed
add solution: linked-list-cycle
1 parent a552e11 commit 1fcdcfc

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

linked-list-cycle/dusunax.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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

0 commit comments

Comments
 (0)