In Floyd’s Cycle-Finding Algorithm (Tortoise and Hare), slow moves by 1 step and fast moves by 2 steps. If a cycle exists, they are guaranteed to meet.
Then comes part 2: to find the start of the cycle (the loop origin), you place one pointer back at the head, keep the other pointer at the meeting_point, and advance both at speed 1. When they meet again, that node is the cycle start. What is the formal modular arithmetic proof that guarantees this?
Here is the production C++20 implementation of Floyd’s Tortoise and Hare Cycle Origin algorithm with pointer safety checks.
Complexity:
O(N)time and strictlyO(1)auxiliary space.Floyd’s cycle algorithm is pure mathematical poetry. Let’s write out the distances with simple algebra so the proof is crystal clear.
1. Defining the Variables
Let’s map out the linked list into three distinct segments:
L: Distance from theheadto the cycle entrance.C: Total length (circumference) of the cycle.x: Distance from the cycle entrance to the meeting point inside the cycle.2. Distance Traveled by Each Pointer
When the Tortoise (slow) and Hare (fast) meet:
Dist_slow = L + xDist_fast = L + n * C + x(wherenis how many full laps fast ran around the cycle).Because the fast pointer moves at twice the speed of slow:
Now subtract
L + xfrom both sides:3. What does L = (n – 1) * C + (C – x) mean?
Look carefully at that equation:
Lis the distance from head to the cycle entrance.(C - x)is the distance from the meeting point to the cycle entrance!(n - 1) * Cis just zero or more full loops around the cycle!Conclusion: If you place Pointer 1 at
head(which must travel distanceL) and Pointer 2 atmeeting_point(which travels distance(C - x)plus some optional full laps), both pointers will meet at the EXACT same node: the cycle entrance!Clean Python 3.12 Implementation
Complexity Breakdown
O(N). Phase 1 takes at most $2N$ steps. Phase 2 takes at most $N$ steps.O(1). No hash set or memory allocation.