Determine whether a singly linked list contains a cycle (a node whose next points back to an earlier node).
Floyd's cycle detection uses slow/fast pointers: if there is a cycle, the fast pointer eventually laps and meets the slow one; if fast reaches null, there is no cycle. O(n) time, O(1) space — no extra visited set needed.
public static boolean hasCycle(Node head) {
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}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 FalseCycle detection guards against infinite loops in linked structures, dependency graphs, and pointer-chasing algorithms.
A candidate stores visited nodes in a HashSet (O(n) space). What is the O(1)-space approach and why does it work?