Optimal Two-Pointer Approach (Floyd's Cycle-Finding Algorithm):
- Use a slow pointer moving 1 step and a fast pointer moving 2 steps; if a cycle exists, they must collide.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def has_cycle(head: ListNode) -> bool:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
Complexity & Key Logic:
- Time Complexity: O(N). In the worst case, fast travels at most 2 times the cycle length to catch slow.
- Space Complexity: O(1) constant auxiliary space.
- Algorithm Details:
- If the list has no cycle, fast or fast.next reaches None, returning False.
- If a cycle exists, fast enters the loop first. With each step, the distance between fast and slow decreases by 1 node until they meet.