🐢🐰 Fast & Slow Pointers

Floyd's Cycle Detection Algorithm

Day 1/6 Pattern: Two Pointers

📖 Pattern Overview

🎯 When to Use

  • Detect cycles in linked lists
  • Find middle of linked list
  • Find duplicate in array
  • Detect loops in sequences

⚡ Complexity

  • Time: O(n)
  • Space: O(1)
  • Advantage: Constant space!
  • Key: Two pointers, different speeds

🔑 How It Works

  • Slow: Moves 1 step at a time 🐢
  • Fast: Moves 2 steps at a time 🐰
  • Cycle: They meet eventually
  • No Cycle: Fast reaches end

🎯 Select Problem

Linked List Cycle Detection

Normal
Slow Pointer 🐢: -
Fast Pointer 🐰: -
Steps Taken: 0
Status: Ready

Current Step:

Click "Start" or "Step" to begin the algorithm

🎨 Custom Input

📚 LeetCode Problems

141. Linked List Cycle

Easy

Detect if a cycle exists in a linked list.

Solve on LeetCode →

142. Linked List Cycle II

Medium

Find the node where the cycle begins.

Solve on LeetCode →

287. Find Duplicate Number

Medium

Find the duplicate in array without modifying it.

Solve on LeetCode →

202. Happy Number

Easy

Determine if a number is happy using cycle detection.

Solve on LeetCode →

876. Middle of Linked List

Easy

Find the middle node using two pointers.

Solve on LeetCode →

457. Circular Array Loop

Medium

Detect loop in a circular array.

Solve on LeetCode →

🧠 Algorithm Deep Dive

Why It Works

If there's a cycle, the fast pointer will eventually "lap" the slow pointer, like runners on a circular track. If there's no cycle, the fast pointer will reach the end.

function hasCycle(head) {
    let slow = head;
    let fast = head;
    
    while (fast && fast.next) {
        slow = slow.next;        // Move 1 step
        fast = fast.next.next;   // Move 2 steps
        
        if (slow === fast) {
            return true;  // Cycle detected!
        }
    }
    
    return false;  // No cycle
}

Finding Cycle Start (Floyd's Algorithm Extended)

After detecting a cycle, reset one pointer to head. Move both at same speed - they meet at the cycle start!

function detectCycle(head) {
    let slow = head, fast = head;
    
    // Phase 1: Detect cycle
    while (fast && fast.next) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow === fast) break;
    }
    
    if (!fast || !fast.next) return null;
    
    // Phase 2: Find start
    slow = head;
    while (slow !== fast) {
        slow = slow.next;
        fast = fast.next;
    }
    
    return slow;  // Cycle start!
}

Real-World Applications

  • Memory Leak Detection: Detect circular references in garbage collection
  • Loop Detection: Find infinite loops in state machines
  • Duplicate Detection: Find duplicates in streams without extra space
  • Network Protocols: Detect routing loops in networking