How would you detect a cycle in a linked list? Implement Floyd's Cycle Detection Algorithm.

🔢 Data Structures And Algorithm• 9/21/2025
Detecting cycles in linked lists using Floyd's tortoise and hare algorithm with implementation details.

Floyd's Cycle Detection Algorithm (Tortoise and Hare)

Algorithm Overview

Use two pointers moving at different speeds:

  • Slow pointer (tortoise): moves one step at a time
  • Fast pointer (hare): moves two steps at a time

Implementation

function hasCycle(head) {
    if (!head || !head.next) return false;
    
    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
}

Time Complexity: O(n)

Space Complexity: O(1)

By: System Admin