Linked listsAnimated
Floyd's Cycle Detection
A slow and a fast pointer meet if and only if there is a cycle.
Time
O(n)
Extra space
O(1)
Use it for
Detecting loops without extra memory.
How it works
- Walk the list with two pointers: slow moves 1 step, fast moves 2 steps.
- If there is no cycle, fast reaches the end (empty).
- If there is a cycle, fast eventually laps slow and they land on the same node.
- It needs no extra memory (O(1)), unlike remembering every visited node in a set.
Watch it run
Loading animation…