Skip to content
Home DSA Detect a Loop in a Linked List: Floyd's Algorithm Explained

Detect a Loop in a Linked List: Floyd's Algorithm Explained

Where developers are forged. · Structured learning · Free forever.
📍 Part of: Linked List → Topic 5 of 10
Detect a loop in a linked list using Floyd's Cycle Detection algorithm.
⚙️ Intermediate — basic DSA knowledge assumed
In this tutorial, you'll learn
Detect a loop in a linked list using Floyd's Cycle Detection algorithm.
  • Floyd's algorithm detects a cycle in O(n) time and O(1) space — the hare gains exactly one step on the tortoise per iteration inside the cycle, so meeting is mathematically guaranteed.
  • The meeting point is NOT the cycle start — you need a second phase: reset one pointer to head, keep the other at the meeting point, advance both one step at a time, and they'll converge exactly at the cycle start.
  • Always guard against hare.next == null before calling hare.next.next — missing this single null check causes NullPointerExceptions on non-cyclic lists with an even node count.
✦ Plain-English analogy ✦ Real code with output ✦ Interview questions
Quick Answer
  • Core idea: slow pointer moves 1 step, fast pointer moves 2 steps. If a cycle exists, they must meet.
  • Mathematical guarantee: inside a cycle of length k, the gap between pointers shrinks by 1 per step — meeting is inevitable within k steps.
  • Two-phase design: Phase 1 detects the cycle (meeting point). Phase 2 finds the exact cycle start node.
  • Space advantage over HashSet: O(1) vs O(n) — critical for constrained environments (kernel code, embedded systems).
  • Production risk: missing null check on fast.next causes NullPointerException on even-length acyclic lists.
  • Biggest mistake: assuming the meeting point is the cycle start — it is not. The second phase is required.
🚨 START HERE
Linked List Cycle Triage Cheat Sheet
Fast commands to diagnose cycle-related production issues.
🟠Thread CPU 100%, suspected infinite loop in linked structure traversal.
Immediate ActionCapture thread dump to identify the spinning thread and its stack trace.
Commands
jcmd <pid> Thread.print
jstack <pid> | grep -A 20 "RUNNABLE"
Fix NowLook for stack frames stuck in while-loops over linked list traversal. Restart the service as a temporary mitigation. Add iteration-count guards as a permanent fix.
🟡Memory leak, suspected cycle keeping detached nodes alive.
Immediate ActionTake a heap dump to analyze reference chains.
Commands
jcmd <pid> GC.heap_dump /tmp/heap.hprof
jmap -dump:format=b,file=/tmp/heap.hprof <pid>
Fix NowUse Eclipse MAT to find Node instances with unexpected inbound references. Look for cycles where nodeA.next -> nodeB and nodeB.next -> nodeA on detached subgraphs.
🟠Service latency spikes with no obvious downstream bottleneck.
Immediate ActionCheck thread dumps for threads in tight CPU loops (RUNNABLE state, no blocking).
Commands
jcmd <pid> Thread.print
top -H -p <pid> (identify which thread is consuming CPU)
Fix NowIf a thread is RUNNABLE with a stack trace in list traversal, suspect a cycle. Add a health-check endpoint that runs Floyd's detection on critical linked structures.
Production IncidentThe Memory Allocator That Spun ForeverA microservice's custom memory pool used a free-list (singly linked list) to track available blocks. A concurrent allocation bug caused two blocks to point to each other, creating a cycle. The allocator's traversal loop never terminated, pegging the thread at 100% CPU and eventually exhausting the service's thread pool.
SymptomService latency spikes to 30s+. Thread dump shows one thread stuck in a tight loop inside FreeListAllocator.allocate(). No exception, no stack overflow — just a while-loop that never exits. CPU on that core at 100%.
AssumptionThe on-call engineer initially suspected a lock contention issue or a downstream dependency timeout, because the thread dump showed no blocking — the thread was actively running.
Root causeA race condition in the concurrent allocation path allowed two threads to claim the same block simultaneously. Thread A set block.next = blockB. Thread B set blockB.next = blockA — creating a two-node cycle in the free-list. The allocator's traversal loop (while current != null) never hit null because current alternated between blockA and blockB forever.
Fix1. Added Floyd's cycle detection as a diagnostic hook — triggered on-demand via a health-check endpoint to verify free-list integrity. 2. Fixed the race condition by introducing a CAS-based allocation path. 3. Added an iteration counter as a circuit breaker: if free-list traversal exceeds 2x expected block count, abort and log a corruption warning. 4. Introduced invariant checks in debug builds that assert the free-list is acyclic after every mutation.
Key Lesson
A cycle in a linked structure causes silent infinite loops — no exception, no crash, just a frozen thread. This is harder to diagnose than a NullPointerException.Always add iteration-count guards on traversal loops over linked structures. A simple counter prevents infinite spin.Concurrent modification of linked structures is the most common cause of cycle creation in production.Floyd's algorithm is not just an interview topic — it is a diagnostic tool for production corruption.
Production Debug GuideSymptom-driven investigation paths for cycle-related incidents.
Thread stuck at 100% CPU in a linked list traversal loop.Capture thread dump to confirm the spinning thread. Check if the loop has a null-termination condition. Suspect a cycle if traversal should have terminated by now.
Memory leak — nodes not garbage collected despite being logically removed.Check for a cycle that keeps nodes reachable from a live reference. A cycle in a detached subgraph prevents GC of all nodes in that cycle.
NullPointerException when traversing a list that should be valid.Check if a previous operation (insertion, deletion, reversal) broke the list chain, creating a dangling pointer. Not a cycle, but a related corruption.
Round-robin scheduler skips or repeats tasks unexpectedly.Verify the circular list invariant: tail.next == head. Check if a concurrent deletion created a cycle or broke the circle.

A cycle in a linked list causes infinite traversal — no stack overflow, no exception, just a frozen thread burning 100% CPU. This is a real production failure mode in memory allocators, graph traversals, and OS schedulers where linked structures are fundamental.

The core problem: given a singly linked list, determine whether following next pointers eventually reaches null (healthy) or loops back to a previously visited node (corrupted). Naive iteration hangs if a cycle exists. A HashSet works but costs O(n) space. Floyd's algorithm solves it in O(1) space using two pointers at different speeds.

Understanding Floyd's is not just interview preparation — it is a debugging primitive. When a production thread spins at 100% CPU on a linked structure, Floyd's reasoning helps you diagnose whether a cycle exists and where it starts.

How to Detect a Loop — Floyd's Cycle Detection

Floyd's Cycle Detection (fast/slow pointer) detects a cycle in a linked list in O(n) time and O(1) space.

Algorithm: 1. Initialize slow = head, fast = head. 2. While fast is not None and fast.next is not None: a. slow = slow.next (1 step). b. fast = fast.next.next (2 steps). c. If slow == fast: cycle detected. Break. 3. If fast or fast.next is None: no cycle.

Finding the cycle start (bonus): 4. After detection, reset slow to head. Keep fast at meeting point. 5. Move both one step at a time until they meet again — the meeting point is the cycle start.

Worked example — list: 1->2->3->4->5->3 (5 points back to 3): Step 1: slow=1, fast=1. Step 2: slow=2, fast=3. Step 3: slow=3, fast=5. Step 4: slow=4, fast=4. (fast: 5.next.next = 3.next.next = ... = 4). Meet at 4! Cycle detected. Reset slow=1. Move both one step: slow=2, fast=5. slow=3, fast=3. Meet at 3. Cycle starts at node 3.

Mental Model
The Track Analogy
Why two speeds guarantee detection
  • Imagine two runners on a circular track. One runs twice as fast.
  • The fast runner gains one lap position per unit time relative to the slow runner.
  • On a track of length k, the fast runner catches the slow runner in at most k steps.
  • The linked list is the track. The cycle is the circular portion. The pointers are the runners.
📊 Production Insight
Floyd's algorithm is a diagnostic primitive, not just a detection tool. In production, expose it as a health-check endpoint on services that maintain linked structures. If a cycle is detected, alert immediately — it indicates a corruption bug, not a normal condition.
🎯 Key Takeaway
Floyd's detection is O(n) time, O(1) space. The fast pointer gains one step per iteration on the slow pointer inside the cycle — meeting is mathematically guaranteed within cycle_length steps.

Why the Naive Approach Breaks — and What We Really Need

The most obvious idea is to use a HashSet: visit each node, store its reference, and if you ever see the same reference twice you've found a cycle. It works. But it costs O(n) extra space — you're storing every node reference you've seen. For a list with millions of nodes, that's a meaningful memory hit, and in constrained environments (embedded systems, kernel code) it's a non-starter.

The other naive approach — setting a maximum iteration count — is fragile. How do you pick the limit? Too small and you get false positives on valid long lists. Too large and a cycle still burns time before you catch it.

What you actually need is an algorithm that uses O(1) space — constant memory regardless of list size — and runs in O(n) time. That's exactly the contract Floyd's Cycle Detection algorithm (also called the tortoise and hare algorithm) delivers. The insight is elegant: instead of remembering where you've been, you use two pointers moving at different speeds and let physics — or rather, modular arithmetic — do the work for you.

Understanding this trade-off (O(n) space HashSet vs O(1) space Floyd's) is precisely what interviewers probe for. Knowing Floyd's exists isn't enough; knowing why you'd choose it is what separates junior from senior.

NaiveLoopDetection.java · JAVA
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
package io.thecodeforge.list;

import java.util.HashSet;
import java.util.Set;

/**
 * Naive cycle detection using a HashSet.
 * Simple but O(n) space — use Floyd's for O(1) space.
 */
public class NaiveLoopDetection {

    // A single node in our linked list
    static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
            this.next = null;
        }
    }

    /**
     * Naive approach: store every visited node reference in a HashSet.
     * If we encounter a node we've already stored, a cycle exists.
     * Time:  O(n)  — we visit each node at most once
     * Space: O(n)  — we store up to n node references
     */
    public static boolean hasCycleNaive(Node head) {
        Set<Node> visitedNodes = new HashSet<>();

        Node current = head;
        while (current != null) {
            // If this node's reference is already in the set, we've looped back
            if (visitedNodes.contains(current)) {
                return true; // cycle detected
            }
            visitedNodes.add(current); // mark this node as visited
            current = current.next;    // move to the next node
        }
        return false; // reached null — no cycle
    }

    public static void main(String[] args) {
        // Build a list: 1 -> 2 -> 3 -> 4 -> 5 -> null  (no cycle)
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        System.out.println("List with no cycle: " + hasCycleNaive(head)); // false

        // Now create a cycle: node 5's next points back to node 3
        // List becomes: 1 -> 2 -> 3 -> 4 -> 5 -> (back to 3)
        head.next.next.next.next.next = head.next.next; // node5.next = node3

        System.out.println("List with cycle:    " + hasCycleNaive(head)); // true
    }
}
▶ Output
List with no cycle: false
List with cycle: true
⚠ Watch Out: References vs Values
The HashSet stores node references (memory addresses), not node values. Two nodes with the same integer value are different objects — the HashSet correctly treats them as distinct. If you accidentally store current.value instead of current, you'll get false cycle detections on lists with duplicate values.
📊 Production Insight
HashSet cycle detection on a 10M-node list allocates ~320MB (assuming 32-byte object header + reference overhead per entry). In a high-throughput service processing thousands of lists per second, this allocation pressure triggers GC thrashing. Floyd's avoids this entirely — two pointers, zero allocation.
🎯 Key Takeaway
The HashSet approach is O(n) space — acceptable for small lists, catastrophic for large ones. Floyd's trades conceptual complexity for O(1) space. In production, the space advantage is not optional — it is the reason Floyd's exists.
Choosing Between HashSet and Floyd's
IfMemory is constrained (embedded, kernel, high-throughput service)
UseUse Floyd's — O(1) space is non-negotiable.
IfClarity is prioritized over memory (prototyping, teaching, one-off scripts)
UseHashSet is acceptable — simpler logic, easier to debug.
IfInterview context
UseStart with HashSet, then optimize to Floyd's. Mention the space trade-off proactively.
IfProduction code with unknown input size
UseAlways Floyd's — HashSet on a 10M-node list allocates ~320MB of references.

Floyd's Cycle Detection — The Tortoise and the Hare

Floyd's algorithm uses two pointers: tortoise moves one step at a time, hare moves two steps at a time. If there's no cycle, the hare reaches null and you're done. If there is a cycle, the hare enters it first and starts lapping the tortoise. Eventually — and this is the key — they must meet inside the cycle.

Why must they meet? Think of it this way: once both pointers are inside the cycle of length k, the hare gains exactly one step on the tortoise per iteration. So the gap between them decreases by one each step. Starting from any gap, you'll hit zero (they meet) in at most k steps. The meeting is guaranteed.

This gives you O(n) time and O(1) space — no HashSet, no counters, just two pointers. That's the win.

One important implementation detail: you must check hare != null AND hare.next != null before advancing the hare two steps. Skipping either check causes a NullPointerException on lists with an even number of nodes — a gotcha that trips up almost every first implementation.

Once they meet, you can go further: find the exact node where the cycle starts. That's the real power of Floyd's, and it's what most tutorials skip.

FloydCycleDetection.java · JAVA
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
package io.thecodeforge.list;

/**
 * Floyd's Cycle Detection with cycle start identification.
 * Production-grade implementation with null guards and phase separation.
 */
public class FloydCycleDetection {

    static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
            this.next = null;
        }
    }

    /**
     * Floyd's Cycle Detection (Tortoise and Hare).
     * Time:  O(n)  — tortoise visits each node at most once before meeting
     * Space: O(1)  — only two pointers, no extra data structures
     *
     * @return the meeting node inside the cycle, or null if no cycle exists
     */
    public static Node detectCycle(Node head) {
        if (head == null || head.next == null) {
            return null; // empty or single-node list can't have a cycle
        }

        Node tortoise = head; // moves 1 step per iteration
        Node hare      = head; // moves 2 steps per iteration

        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;       // 1 step
            hare     = hare.next.next;      // 2 steps

            // If they meet, a cycle exists — return the meeting point
            if (tortoise == hare) {
                return tortoise;
            }
        }

        // hare hit null — no cycle
        return null;
    }

    /**
     * Find the node where the cycle STARTS (not just whether one exists).
     *
     * Mathematical proof sketch:
     *   Let F = distance from head to cycle start
     *       C = length of the cycle
     *       h = distance from cycle start to meeting point (inside cycle)
     *
     *   When they meet:  tortoise travelled F + h
     *                    hare travelled    F + h + n*C  (lapped the cycle n times)
     *   Since hare travels 2x as far:  2(F + h) = F + h + n*C
     *   Simplifying:                   F = n*C - h
     *   This means: a pointer starting at head AND a pointer starting at the
     *   meeting point, both moving one step at a time, will meet exactly at
     *   the cycle start node.
     */
    public static Node findCycleStart(Node head) {
        Node meetingPoint = detectCycle(head);
        if (meetingPoint == null) {
            return null; // no cycle
        }

        Node pointerFromHead    = head;         // starts at the beginning
        Node pointerFromMeeting = meetingPoint; // starts at the meeting point

        // Both move one step at a time — they converge at the cycle start
        while (pointerFromHead != pointerFromMeeting) {
            pointerFromHead    = pointerFromHead.next;
            pointerFromMeeting = pointerFromMeeting.next;
        }

        return pointerFromHead; // this is the cycle start node
    }

    public static void main(String[] args) {
        // Build list: 10 -> 20 -> 30 -> 40 -> 50
        //                          ^              |
        //                          |______________|  (cycle starts at node 30)
        Node head    = new Node(10);
        Node node20  = new Node(20);
        Node node30  = new Node(30); // <-- cycle start
        Node node40  = new Node(40);
        Node node50  = new Node(50);

        head.next   = node20;
        node20.next = node30;
        node30.next = node40;
        node40.next = node50;
        node50.next = node30; // cycle: 50 points back to 30

        // --- Detect cycle ---
        Node meeting = detectCycle(head);
        if (meeting != null) {
            System.out.println("Cycle detected! Meeting point value: " + meeting.value);
        } else {
            System.out.println("No cycle found.");
        }

        // --- Find cycle start ---
        Node cycleStart = findCycleStart(head);
        if (cycleStart != null) {
            System.out.println("Cycle starts at node with value: " + cycleStart.value);
        }

        // --- Verify on a clean list ---
        Node cleanHead = new Node(1);
        cleanHead.next = new Node(2);
        cleanHead.next.next = new Node(3);
        System.out.println("Clean list cycle detected: " + (detectCycle(cleanHead) != null));
    }
}
▶ Output
Cycle detected! Meeting point value: 40
Cycle starts at node with value: 30
Clean list cycle detected: false
🔥Interview Gold: Meeting Point Is Not Cycle Start
The meeting point value (40) varies depending on relative speeds and cycle length — don't assume it equals the cycle start. The second phase (resetting one pointer to head) is what pins down the exact start. If an interviewer asks you to find where the cycle begins, this two-phase approach is exactly what they want.
📊 Production Insight
The null guard hare != null && hare.next != null is not optional — it is the difference between a correct algorithm and a NullPointerException. In production, wrap Floyd's in a try-catch as a safety net, but the primary defense is the correct guard condition. Missing hare.next != null fails on any acyclic list with an even number of nodes.
🎯 Key Takeaway
Floyd's two-phase design is compositional: Phase 1 detects the cycle, Phase 2 locates the start. The meeting point is never the cycle start (except when F=0). Always implement both null guards — hare != null and hare.next != null.
Two-Phase Floyd's: What Each Phase Gives You
IfPhase 1: tortoise meets hare
UseConfirms a cycle exists. Returns a meeting point inside the cycle (not the start).
IfPhase 2: reset one pointer to head, advance both one step
UseConvergence point is the exact cycle start node. This is where the list enters the cycle.
IfNeed only cycle existence (not start location)
UsePhase 1 alone is sufficient. Skip Phase 2 for a simpler implementation.
IfNeed to remove the cycle
UseRun Phase 2 to find the start. Then find the last node in the cycle (one whose next == cycleStart) and set its next to null.

Finding Cycle Length — The Bonus Move Most Candidates Miss

Once you can detect a cycle and find its start node, measuring the cycle's length is trivial — and it's a common follow-up question that catches people off guard.

After finding the cycle start node, simply walk from that node one step at a time, counting steps until you return to the same node. Since you're guaranteed to be inside the cycle, you'll complete exactly one full loop and your step count is the cycle length.

This is useful in real scenarios too: imagine a round-robin task scheduler implemented as a circular linked list. Knowing the number of tasks (cycle length) lets you calculate time slots correctly without re-traversing the entire structure from scratch.

Notice how the three operations — detect, find start, measure length — compose naturally. Each one builds on the previous. That compositional design is intentional. In interviews, demonstrating that you see these as related operations rather than isolated tricks signals strong algorithmic thinking.

Time complexity remains O(n) overall. The cycle-length measurement adds at most O(k) where k ≤ n, so the bound doesn't change.

CycleLengthFinder.java · JAVA
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
package io.thecodeforge.list;

/**
 * Extends Floyd's detection with cycle length measurement.
 * Compositional design: detect -> find start -> measure length.
 */
public class CycleLengthFinder {

    static class Node {
        int value;
        Node next;

        Node(int value) {
            this.value = value;
            this.next = null;
        }
    }

    // --- Reuse Floyd's detection from earlier ---
    public static Node detectCycle(Node head) {
        if (head == null || head.next == null) return null;

        Node tortoise = head;
        Node hare     = head;

        while (hare != null && hare.next != null) {
            tortoise = tortoise.next;
            hare     = hare.next.next;
            if (tortoise == hare) return tortoise;
        }
        return null;
    }

    public static Node findCycleStart(Node head) {
        Node meetingPoint = detectCycle(head);
        if (meetingPoint == null) return null;

        Node fromHead    = head;
        Node fromMeeting = meetingPoint;

        while (fromHead != fromMeeting) {
            fromHead    = fromHead.next;
            fromMeeting = fromMeeting.next;
        }
        return fromHead;
    }

    /**
     * Measures the number of nodes in the cycle.
     * Strategy: start at the cycle's first node, walk until we return to it.
     * The step count equals the cycle length.
     */
    public static int measureCycleLength(Node head) {
        Node cycleStart = findCycleStart(head);
        if (cycleStart == null) {
            return 0; // no cycle
        }

        int cycleLength = 1;              // we count the start node itself
        Node walker = cycleStart.next;    // begin one step ahead

        // Walk until we lap back to cycleStart
        while (walker != cycleStart) {
            walker = walker.next;
            cycleLength++;
        }

        return cycleLength;
    }

    public static void main(String[] args) {
        // Build: 5 -> 10 -> 15 -> 20 -> 25 -> 30
        //                    ^                  |
        //                    |__________________| (cycle of length 4: 15->20->25->30->15)
        Node head   = new Node(5);
        Node node10 = new Node(10);
        Node node15 = new Node(15); // cycle start
        Node node20 = new Node(20);
        Node node25 = new Node(25);
        Node node30 = new Node(30);

        head.next   = node10;
        node10.next = node15;
        node15.next = node20;
        node20.next = node25;
        node25.next = node30;
        node30.next = node15; // close the cycle at node15

        System.out.println("Cycle detected : " + (detectCycle(head) != null));
        System.out.println("Cycle starts at: " + findCycleStart(head).value);
        System.out.println("Cycle length   : " + measureCycleLength(head) + " nodes");

        // Bonus: no-cycle case
        Node cleanList = new Node(1);
        cleanList.next = new Node(2);
        cleanList.next.next = new Node(3);
        System.out.println("Clean list cycle length: " + measureCycleLength(cleanList));
    }
}
▶ Output
Cycle detected : true
Cycle starts at: 15
Cycle length : 4 nodes
Clean list cycle length: 0
💡Pro Tip: Off-by-One Guard
When measuring cycle length, initialise cycleLength = 1 and start walker at cycleStart.next. This way the while-loop condition walker != cycleStart is correct on the very first check, even if the cycle has length 1 (a node pointing to itself). If you initialise to 0 and start at cycleStart, you need a do-while — which is easy to forget and causes an off-by-one.
📊 Production Insight
In a round-robin scheduler implemented as a circular linked list, knowing the cycle length lets you pre-allocate time slots without traversing the entire list on each scheduling decision. If the cycle length changes (task added/removed), re-measure. Cache the result and invalidate on mutation.
🎯 Key Takeaway
Cycle length measurement is a free extension of Floyd's pipeline. The three operations (detect, find start, measure length) compose naturally — each builds on the previous. Total complexity remains O(n).
Composing Floyd's Operations
IfNeed only cycle existence check
UseRun detectCycle() only. O(n) time, O(1) space. Returns meeting point or null.
IfNeed cycle start location
UseRun detectCycle() then findCycleStart(). Two-phase. O(n) time, O(1) space.
IfNeed cycle length
UseRun full pipeline: detectCycle() -> findCycleStart() -> measureCycleLength(). O(n) time, O(1) space.
IfNeed to break the cycle
UseFind cycle start. Walk from start to find the last node (node.next == cycleStart). Set lastNode.next = null.
🗂 HashSet vs Floyd's Algorithm
Trade-offs for production and interview contexts.
AspectHashSet ApproachFloyd's Algorithm
Time ComplexityO(n)O(n)
Space ComplexityO(n) — stores all node refsO(1) — just two pointers
Can Find Cycle Start?Yes — the first duplicate foundYes — requires second phase
Can Find Cycle Length?Yes — counts stored refs in cycleYes — walk from cycle start
Handles Null Head?Yes — loop never executesYes — explicit null check needed
Code ComplexitySimple — straightforward logicModerate — non-obvious math
Best Used WhenClarity matters more than memoryMemory is constrained (O(1) required)
Interview PreferenceAcceptable as first answerExpected as optimised solution
GC Pressure on Large ListsHigh — HashSet allocates per nodeZero — no allocations
Thread SafetyRequires ConcurrentHashMap for concurrent useInherently read-only — safe for concurrent detection

🎯 Key Takeaways

  • Floyd's algorithm detects a cycle in O(n) time and O(1) space — the hare gains exactly one step on the tortoise per iteration inside the cycle, so meeting is mathematically guaranteed.
  • The meeting point is NOT the cycle start — you need a second phase: reset one pointer to head, keep the other at the meeting point, advance both one step at a time, and they'll converge exactly at the cycle start.
  • Always guard against hare.next == null before calling hare.next.next — missing this single null check causes NullPointerExceptions on non-cyclic lists with an even node count.
  • Cycle length is a free bonus: once you have the cycle start node, count steps back to it in one pass — useful for round-robin schedulers, circular buffer implementations, and graph analysis.

⚠ Common Mistakes to Avoid

    Not checking `hare.next != null` before calling `hare.next.next` — This causes a NullPointerException on any list with an even number of nodes, because the hare lands on the last node (not null) and then tries to call `.next` on null. Fix: always write `while (hare != null && hare.next != null)` — both guards are required.
    Fix

    always write while (hare != null && hare.next != null) — both guards are required.

    Returning `tortoise == hare` immediately at the start when both begin at `head` — Since both pointers start at the same node, your first equality check fires before either pointer moves, and you incorrectly report a cycle on every non-empty list. Fix: advance both pointers *before* the equality check, or use a do-while loop that moves first and checks after.
    Fix

    advance both pointers before the equality check, or use a do-while loop that moves first and checks after.

    Assuming the meeting point *is* the cycle start — The meeting point is somewhere inside the cycle, but almost never at the start (unless F=0, meaning the cycle starts at head). Fix: after detecting the meeting point, reset one pointer to head and advance both one step at a time until they meet — *that* convergence point is the true cycle start.
    Fix

    after detecting the meeting point, reset one pointer to head and advance both one step at a time until they meet — that convergence point is the true cycle start.

    Storing node values instead of node references in the HashSet approach — Two nodes with the same integer value are different objects. Storing `current.value` causes false positives on lists with duplicate values. Fix: always store `current` (the reference), never `current.value`.
    Fix

    always store current (the reference), never current.value.

    No iteration-count guard on production traversal — Even with Floyd's detection, a corrupted list with a very long cycle can cause the detection phase to run longer than expected. Fix: add a maximum iteration counter that throws an exception if traversal exceeds 2x expected list size.
    Fix

    add a maximum iteration counter that throws an exception if traversal exceeds 2x expected list size.

Interview Questions on This Topic

  • QCan you explain why Floyd's algorithm is guaranteed to detect a cycle — not just that it does, but the mathematical reason the hare must eventually catch the tortoise?
  • QAfter using Floyd's algorithm to find a meeting point inside the cycle, how do you find the node where the cycle begins? Walk me through the proof of why resetting one pointer to head works.
  • QWhat happens if you use a hare that moves 3 steps instead of 2 — does the algorithm still work? What changes?
  • QHow would you modify Floyd's algorithm to detect a cycle in a doubly linked list? Does the prev pointer help or complicate things?
  • QIf you detect a cycle, how would you remove it in O(1) space without using Floyd's second phase? What are the trade-offs?

Frequently Asked Questions

What is the time and space complexity of Floyd's cycle detection algorithm?

Floyd's algorithm runs in O(n) time because in the worst case the tortoise visits each node once before the pointers meet. The space complexity is O(1) because you only use two pointer variables regardless of list size — no extra data structures are needed.

Can Floyd's algorithm detect a cycle if the cycle starts at the very first node (the head)?

Yes. When the cycle starts at head, the distance F (from head to cycle start) is zero. In the second phase, resetting one pointer to head means both pointers are already at the cycle start immediately — they meet on the first comparison, correctly identifying head as the cycle start.

Why does the second phase of Floyd's algorithm (resetting one pointer to head) find the cycle start?

The math works out to F = nC - h, where F is the distance from head to cycle start, C is the cycle length, and h is the distance from cycle start to the meeting point. This means a pointer walking from head and a pointer walking from the meeting point cover the same logical distance before reaching the cycle start, so they arrive there simultaneously.

Why does Floyd's algorithm work — why do they always meet inside the cycle?

Once both pointers enter the cycle, fast closes in on slow at 1 step per round (fast moves 2, slow moves 1, so the gap shrinks by 1 per step). Since the cycle has finite length, fast will catch slow within at most cycle_length steps after both enter the cycle.

How do you find the length of the cycle?

After slow and fast meet, keep fast stationary and advance slow one step at a time, counting steps until slow returns to the meeting point. The count is the cycle length.

What happens if the hare moves 3 steps instead of 2?

The algorithm still works — the hare still gains on the tortoise (2 steps per iteration instead of 1), so they still meet. However, the meeting point changes, and the second-phase proof must be adjusted. The 2-step hare is preferred because it minimizes iterations and simplifies the mathematical proof.

🔥
Naren Founder & Author

Developer and founder of TheCodeForge. I built this site because I was tired of tutorials that explain what to type without explaining why it works. Every article here is written to make concepts actually click.

← PreviousReverse a Linked ListNext →Merge Two Sorted Linked Lists
Forged with 🔥 at TheCodeForge.io — Where Developers Are Forged