Two pointers do not need to move together. In a linked list, one pointer can move one step while another moves two.
Different speeds reveal a cycle
If the list ends, the fast pointer eventually reaches the end. If the list loops, the fast pointer keeps circling and must eventually meet the slow pointer.
- Slow moves one link at a time.
- Fast moves two links at a time.
- Equal pointers mean they met inside a cycle.
- A missing fast link means the list ends normally.
Use constant extra memory
def has_cycle(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseThe same speed difference finds the middle of a normal list: when fast reaches the end, slow is halfway there.
This pattern replaces a set of visited nodes with movement rules, reducing extra space from O(n) to O(1).
Your tiny challenge
Draw six linked nodes. Move slow one step and fast two steps until fast ends. Which node does slow reach?
