Floyd's cycle finding algorithm
- Introduction
- Linked list with a cycle
- Proof
- Modulo arithmetic
- Code implementation
- Interactive Demo
- References
Introduction
Floyd’s cycle finding algorithm or tortoise and hare algorithm finds cycles in a linked list. If there is a cycle in a linked list, a slow pointer can meet up with the fast pointer. An analogy would be that the slow tortoise has “caught up” with the fast hare.
Linked list with a cycle
Let $a$ be the distance from the start node to the cycle start node, $b$ the distance from the cycle start node to the meet node and $T$ be the cycle length.
Slow pointer $p_1$ moves 1 node at each time step. Fast pointer $p_2$ moves 2 nodes at each time step.
- If there is no cycle, $p_2$ will reach the end(last) node first.
- If there is a cycle, both pointers meet at a node within the cycle.
Proof
\(\begin{aligned} Distance(p_1) &= a + b + k_1T\\ Distance(p_2) &= a + b + k_2T\\ Distance(p_2) &= 2Distance(p_1)\\ a + b + k_2T &= 2(a + b + k_1T)\\ a + b &= (k_2-2k_1)T\\ a &= (k_2-2k_1)T - b\\ a &= kT - b\\ &where \ k_1<k_2, k_1, k_2, k \in \mathbb{Z}^{+}\\ \end{aligned}\) Since $k$ is an non-negative integer, both pointers meet at a node within the cycle. Hence
Note that when both pointers meet, the fast pointer is $b$ steps ahead of the cycle start node. Hence, if the fast pointer advances $a$ steps forward, it will be at the cycle start node. If we reset the slow pointer to the start node, and advance both pointers 1 step at a time, both pointers will meet at the cycle start node.
Modulo arithmetic
Position of fast pointer (with respect to cycle index) is essentially \(\begin{aligned} (D-a) \ mod \ T\\ \end{aligned}\) Position of fast pointer (with respect to node index) is essentially \(\begin{aligned} a + (D-a) \ mod \ T\\ \end{aligned}\) where $D$ is the distance from start node, $a$ the distance from start node to the cycle start node, $T$ is the cycle period.
Code implementation
Interactive Demo
1
1