Two PointersTwo Pointers

Fast & Slow Pointers (Floyd's Cycle Detection)

Advance one pointer twice as fast as another through a linked structure to find cycles, cycle starts, midpoints, and k-th-from-end nodes in O(1) space.

Learn Fast & Slow Pointers →
headslowfast
1
2
3
4
5
6
7
1/10The tail links back to index 3, forming a cycle — but the algorithm does not know that. Start slow and fast at head; fast moves two nodes per step, slow one.
slow (1 step)fast (2 steps)Meeting point / bothCycle start
1slow = fast = head
2while fast and fast.next:
3 slow = slow.next; fast = fast.next.next
4 if slow == fast: break # cycle found
5if no meeting: return no cycle
6p = head; while p != slow: p = p.next; slow = slow.next
7return p # cycle start
Variables
step0
Complexity
best O(n)
avg O(n)
worst O(n)
space O(1)
Speed