Video in progress
How do you detect a cycle in a linked list without extra memory?
Floyd's method: the slow pointer moves one step, the fast pointer moves two. If there is a cycle, they are guaranteed to meet; if the fast pointer reaches null, there is no cycle. O(n) time, O(1) memory.
📖 Answer
The simplest solution is to collect the visited nodes in a HashSet. It works, but it takes O(n) memory. The interviewer then asks "what about without extra memory?".
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;
}
Why do they meet? Once both are inside the cycle, the fast pointer closes in on the slow one by one step per iteration. Because the distance shrinks by one at a time, it can't "jump over" it.
Note that slow == fast compares references, not values. A list can have two nodes with the same value.
A follow-up that's often asked: finding where the cycle begins. After they meet, you move one pointer back to the head and advance both one step at a time; they meet at the start of the cycle.
Sign up to mark studied questions and save your progress.