Skip to content

Commit d2b4bdf

Browse files
leetcode 141
1 parent c6cc576 commit d2b4bdf

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

Leetcode/Leetcode_141.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""
2+
LeetCode 141. Linked List Cycle
3+
4+
Problem:
5+
Given the head of a linked list, determine if the linked list has a cycle in it.
6+
7+
A cycle exists if some node in the list can be reached again by continuously
8+
following the next pointers.
9+
10+
Approach: Floyd's Cycle Detection Algorithm (Tortoise and Hare)
11+
12+
1. Initialize two pointers:
13+
- slow -> moves one step at a time
14+
- fast -> moves two steps at a time
15+
16+
2. Traverse the list:
17+
- Move slow by one node.
18+
- Move fast by two nodes.
19+
20+
3. If there is a cycle:
21+
- fast will eventually catch up to slow.
22+
- slow == fast, so return True.
23+
24+
4. If there is no cycle:
25+
- fast or fast.next becomes None.
26+
- Return False.
27+
28+
Why it works:
29+
- Inside a cycle, the fast pointer gains one node on the slow pointer
30+
during each iteration.
31+
- Eventually, the fast pointer will meet the slow pointer.
32+
33+
Time Complexity: O(n)
34+
- Each pointer traverses at most O(n) nodes.
35+
36+
Space Complexity: O(1)
37+
- No extra data structures are used.
38+
39+
Example:
40+
Input:
41+
3 -> 2 -> 0 -> -4
42+
^ |
43+
|_________|
44+
45+
Output:
46+
True
47+
"""
48+
49+
# Definition for singly-linked list.
50+
# class ListNode:
51+
# def __init__(self, x):
52+
# self.val = x
53+
# self.next = None
54+
55+
class Solution:
56+
def hasCycle(self, head: Optional[ListNode]) -> bool:
57+
# Initialize both pointers at the head
58+
slow = head
59+
fast = head
60+
61+
# Continue while fast can move two steps
62+
while fast and fast.next:
63+
64+
# Move slow by one step
65+
slow = slow.next
66+
67+
# Move fast by two steps
68+
fast = fast.next.next
69+
70+
# If both pointers meet, a cycle exists
71+
if slow == fast:
72+
return True
73+
74+
# Reached the end of the list, so no cycle exists
75+
return False

0 commit comments

Comments
 (0)