Linked List Cycle II - Solution
Solutions and explanations
Video Explanation
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
visited = set()
cur = head
while cur:
if cur in visited:
return cur # Cycle entry found
visited.add(cur)
cur = cur.next
return None # No Cycle
Complexity Analysis
Here, n is the number of elements in the linked list.
- Time Complexity:
O(n) - Space Complexity:
O(n)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
# Step 1: Detect the cycle
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break # cycle detected
else: # else runs only if the while loop ends naturally without 'break'
return None # no cycle
# Step 2: Find the start node of the cycle
slow1 = head
while slow != slow1:
slow = slow.next
slow1 = slow1.next
return slow
Complexity Analysis
Here, n is the number of elements in the linked list.
- Time Complexity:
O(n) - Space Complexity:
O(1)