5.3 Floyd's Cycle Detection, Entry Proof & Loop Removal
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Runners on a Track With a Circular Loopβ
Picture two runners starting from a linear trail leading into a closed circular stadium track β one jogging speed (slow) and the other sprinting speed (fast). If the track terminates cleanly at a finish ribbon (NULL), the sprinter hits the finish ribbon safely. If the path loops back into a closed circular stadium, the sprinter cannot escape and is mathematically guaranteed to lap and collide with the jogger inside the loop!
π» Bridging to Computer Science: Three-Phase Constant-Space Loop Repairβ
Checking every visited node with a Hash Set (unordered_set<Node*>) detects cycles in RAM. Floyd's Cycle-Finding Algorithm detects cycles, locates the exact Cycle Entry node, AND breaks the loop cleanly back to NULL using strictly extra space!
βΎοΈ Cycle Geometry: Prefix Length L and Cycle Length Cβ
π¬ Phase 1 & Phase 2 Mathematical Proofsβ
Once both pointers reside inside a cycle of nodes, each iteration advances fast nodes and slow node, decreasing circular distance cleanly by node per tick. Because closure step size is strictly , fast can NEVER step over slow β collision is guaranteed within at most ticks inside the cycle.
Let be the prefix steps from head to Cycle Entry, be the steps from Cycle Entry to Collision Point, and be cycle circumference:
Because :
Resetting slow = head while keeping fast at Collision Point and walking both at speed forces slow to cover steps precisely when fast covers full laps plus forward steps β colliding directly on Cycle Entry!
Phase 3: Safe Loop Removal in Cβ
struct Node* detectLocateAndBreakCycle(struct Node *head) {
struct Node *slow = head, *fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) break; // Phase 1: Cycle Detected!
}
if (fast == NULL || fast->next == NULL) return NULL;
slow = head; // Phase 2: Find Entry
while (slow != fast) {
slow = slow->next;
fast = fast->next;
}
struct Node *cycleEntry = slow;
while (fast->next != cycleEntry) { // Phase 3: Walk around loop tail
fast = fast->next;
}
fast->next = NULL; // Sever corrupt back-edge cleanly
return cycleEntry;
}
π Real-World Production Context: Deadlock Detection & Cycle Auditsβ
Cycle Detection Engines Beyond Linked Lists
Floyd's O(1)-RAM state-machine loop detection extends directly into cryptography, PRNGs, and database lock monitors
Wait-For Graph Deadlock Loops
Database Lock Managers- Walks single-waiter lock-ownership chains cleanly in O(1) memory without extra hash allocations.
- Identifies the exact cycle-entry holder transaction for minimal rollback victim selection.
Pollard's Rho Factorization & PRNG Audits
Cryptography / Random Streams- Measures period C and tail length L of deterministic sequences x_(i+1) = f(x_i) in O(1) RAM.
- Factors giant RSA-scale semiprimes faster than brute-force division via Birthday collision loops.
Duplicate Number In Immutable Arrays
O(1) Space Indexing Trick- Treats values 1..n in an n+1 read-only array as next-pointers A[i] -> A[A[i]].
- Pigeonhole guarantees a cycle whose Entry Node equals the exact repeated integer in O(n) time, O(1) RAM!
π Numerical Applications & Worked Examplesβ
A 10-node singly linked list links 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10, with tail 10->next = Node 4:
- Determine , , and trace Phase 1 (
slow += 1, fast += 2fromNode 1) to locate the exact collision node. - Trace Phase 2 (
slow = 1, both ) to prove they collide atNode 4, then state which node's.nextpointer Phase 3 overwrites withNULL.
Step-by-Step Solution:β
-
Parameters & Phase 1 Trace: (
1->2->3->4), (4..10):- Step 0:
(1, 1)-> Step 1:(2, 3)-> Step 2:(3, 5)-> Step 3:(4, 7)-> Step 4:(5, 9)-> Step 5:(6, 4)-> Step 6:(7, 6)-> Step 7:(8, 8)Collision! - Notice (
4 -> 8), so !
- Step 0:
-
Phase 2 & Phase 3:
- Phase 2:
(1, 8) -> (2, 9) -> (3, 10) -> (4, 4)β converges strictly on EntryNode 4! - Phase 3 walks around from
4untilfast->next == 4(stops atNode 10) and setsNode 10->next = NULL!
- Phase 2:
π― Exam & Interview Pitfall Checkβ
- Why can't
fasthop+3steps instead of+2in Floyd's Algorithm?- Velocity gap does NOT guarantee hitting
slowcleanly β if a loop has even length and initial offset gap is odd, -step leaps forever step right overslow! Relative closure speed$1$(fast += 2, slow += 1) guarantees collision!
- Velocity gap does NOT guarantee hitting
- In
L = 3, C = 7, how do you calculate exact cycle length once collision happens?- Keep
slowfrozen at Collision Node and walkfast = fast->nextcounting ticks untilfast == slowagain β that exact step count equals !
- Keep
- Forgetting Special Case
L = 0(Full Loop Back toHEAD): Whentail->next == head, Phase 2 starts withslow == fast == headimmediately (0iterations)! In naive break codewhile (fast->next != head)carefully runs around the loop once cleanly β never blindly move both pointers beforewhile (slow != fast)! - Condition Order Crash (
fast->next != NULL && fast != NULL): Reversing operands crashes cleanly on acyclic lists ending atfast == NULL. Always testfast != NULLfirst! - Stopping Loop Break Inside
while (slow != fast)Without Walking to Cycle Tail: Resettingentry->next = NULLinstead ofpred->next = NULLsevers the entire cycle! Wait untilfast->next == cycleEntrybefore nulling!
π Navigation & Next Stepsβ
Next, we upgrade from single-direction chains to bidirectional pointers in Topic 5.4 β Doubly Linked Lists & Constant-Time Node Splicing.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.