Skip to main content

5.3 Floyd's Cycle Detection, Entry Proof & Loop Removal

πŸ“šModule 05 β€’ Linked ListsTopic 5.3⏱️13 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 1Γ—1\times speed (slow) and the other sprinting 2Γ—2\times 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 O(n)\mathcal{O}(n) RAM. Floyd's Cycle-Finding Algorithm detects cycles, locates the exact Cycle Entry node, AND breaks the loop cleanly back to NULL using strictly O(1)\mathcal{O}(1) extra space!


♾️ Cycle Geometry: Prefix Length L and Cycle Length C​


πŸ”¬ Phase 1 & Phase 2 Mathematical Proofs​

πŸ“Phase 1 Proof: Guaranteed Rendezvous Closuretheorem

Once both pointers reside inside a cycle of CC nodes, each iteration advances fast +2+2 nodes and slow +1+1 node, decreasing circular distance cleanly by 2βˆ’1=12 - 1 = 1 node per tick. Because closure step size is strictly 11, fast can NEVER step over slow β€” collision is guaranteed within at most CC ticks inside the cycle.

πŸ“Phase 2 Proof: Finding the Exact Cycle Entry Nodetheorem

Let LL be the prefix steps from head to Cycle Entry, dd be the steps from Cycle Entry to Collision Point, and CC be cycle circumference: Dslow=L+dDfast=L+kβ‹…C+d(kβ‰₯1)D_{\text{slow}} = L + d \qquad D_{\text{fast}} = L + k \cdot C + d \quad (k \ge 1) Because Dfast=2β‹…DslowD_{\text{fast}} = 2 \cdot D_{\text{slow}}: L+kβ‹…C+d=2L+2dβ€…β€ŠβŸΉβ€…β€ŠL=kβ‹…Cβˆ’d=(kβˆ’1)C+(Cβˆ’d)L + k \cdot C + d = 2L + 2d \implies L = k \cdot C - d = (k - 1)C + (C - d) Resetting slow = head while keeping fast at Collision Point and walking both at 1Γ—1\times speed forces slow to cover LL steps precisely when fast covers (kβˆ’1)(k-1) full laps plus (Cβˆ’d)(C - d) 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​

πŸ“Problem Statement: Phase 1 & Phase 2 Full Trace on L = 3, C = 7theorem

A 10-node singly linked list links 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10, with tail 10->next = Node 4:

  1. Determine LL, CC, and trace Phase 1 (slow += 1, fast += 2 from Node 1) to locate the exact collision node.
  2. Trace Phase 2 (slow = 1, both +1+1) to prove they collide at Node 4, then state which node's .next pointer Phase 3 overwrites with NULL.

Step-by-Step Solution:​

  1. Parameters & Phase 1 Trace: L=3L = 3 (1->2->3->4), C=7C = 7 (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 d=4d = 4 (4 -> 8), so Cβˆ’d=7βˆ’4=3=LC - d = 7 - 4 = 3 = L!
  2. Phase 2 & Phase 3:

    • Phase 2: (1, 8) -> (2, 9) -> (3, 10) -> (4, 4) β€” converges strictly on Entry Node 4!
    • Phase 3 walks around from 4 until fast->next == 4 (stops at Node 10) and sets Node 10->next = NULL!

🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Why can't fast hop +3 steps instead of +2 in Floyd's Algorithm?
    • Velocity gap 3βˆ’1=23 - 1 = 2 does NOT guarantee hitting slow cleanly β€” if a loop has even length CC and initial offset gap is odd, 22-step leaps forever step right over slow! Relative closure speed $1$ (fast += 2, slow += 1) guarantees collision!
  2. In L = 3, C = 7, how do you calculate exact cycle length CC once collision happens?
    • Keep slow frozen at Collision Node and walk fast = fast->next counting ticks until fast == slow again β€” that exact step count equals CC!
Common Interview Traps: Architectural Trade-Offs
  • Forgetting Special Case L = 0 (Full Loop Back to HEAD): When tail->next == head, Phase 2 starts with slow == fast == head immediately (0 iterations)! In naive break code while (fast->next != head) carefully runs around the loop once cleanly β€” never blindly move both pointers before while (slow != fast)!
  • Condition Order Crash (fast->next != NULL && fast != NULL): Reversing operands crashes cleanly on acyclic lists ending at fast == NULL. Always test fast != NULL first!
  • Stopping Loop Break Inside while (slow != fast) Without Walking to Cycle Tail: Resetting entry->next = NULL instead of pred->next = NULL severs the entire cycle! Wait until fast->next == cycleEntry before 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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.