Detect a cycle (Floyd’s algorithm)
Easy TimeO(n) SpaceO(1)
Following a well-formed list eventually reaches the end. If some node points back to one already visited the walk never finishes, and the list has a cycle. Given the head of a list, return true when it contains one. The cycle need not include the head — it can start anywhere — an empty list has none, and the memory used must not grow with the length of the list.
Examples
Example 1
- Input
- head = buildCyclicList()
- Output
- The fourth node points back at the second, so the walk never reaches an end.
true
Example 2
- Input
- head = { val: 1, next: { val: 2, next: null } }
- Output
- Two nodes and then
falsenull: the walk finishes, so there is no cycle.
The Code
function buildCyclicList() {
const a = { val: 1, next: null };
const b = { val: 2, next: null };
const c = { val: 3, next: null };
const d = { val: 4, next: null };
a.next = b;
b.next = c;
c.next = d;
d.next = b;
return a;
}
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast && fast.next) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
hasCycle(buildCyclicList());Done
More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Merge two lists A dummy head removes every special case for the first node.
- Remove nth from end Open an n-node gap between two pointers, then walk them together.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.
- Merge k lists Merge lists in pairs, halving how many remain each round.