Skip to main content
PreparationZone Logo
PreparationZone
Back to Fundamentals

Fundamentals · Medium · Free

How do you detect a cycle in a linked list (Floyd)?

FresherFundamentalsData Structures & Algorithms
Model answer

Floyd cycle detection

Slow moves 1 step, fast 2 steps—if they meet, cycle exists. O(n) time, O(1) space.

java
boolean hasCycle(ListNode head) {
  ListNode slow = head, fast = head;
  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast) return true;
  }
  return false;
}
Follow-up: find cycle start node—reset one pointer to head.