DrawCode Algorithm Visualizer • Linked List • Easy

Floyd's Cycle Detection

Tags: Linked List, Two Pointers, Cycle, Floyd

1. One-Liner

Floyd’s algorithm moves a slow pointer one step and a fast pointer two steps; they meet iff a cycle exists.


2. The Problem It Solves

Detect cycles in linked structures without extra memory—important for memory leak checks, list integrity, and interview classics.


3. The Core Idea

If there is a cycle, the fast runner eventually enters the loop and catches the slow one inside; if null-terminated, fast reaches end first.


4. How It Works (Step-by-Step)

StepAction
1slow=fast=head
2While fast and fast.next: advance slow by 1, fast by 2
3If slow==fast → cycle
4Else end → no cycle

5. Dry Run Example

List 1→2→3→2 (back): slow and fast meet at some node inside the loop after finite steps.


6. Key Properties

PropertyDetail
SpaceO(1) pointers only
TimeO(n) meet time
PhaseDetection only; entry node needs extra step

7. Where It Is Used

Domain / SystemUse
RuntimesCycle in linked structures
DatabasesRow chains
SecurityPointer validation

8. Interview Tips

Follow-up: start of cycle using meeting point + second pointer from head. Know why fast=3x also works but different analysis.


9. Comparison with Other Algorithms

TechniqueNotes
Hash set of nodesO(n) memory
Brent’s algorithmAlternative stepping
DFS on graphDifferent model

10. Complexity

----
TimeO(n)
SpaceO(1)

Implementation Example (PYTHON)

class ListNode:
    def __init__(self, x): self.val = x; self.next = None

def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            return True
    return False

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer