← All posts
postApril 8, 2026
Detect a Cycle in a Linked List
#javascript#linked-list#two-pointers#algorithms
Medium⏱️ Logic Challenge
Implement hasCycle(head) for a singly linked list. Each node has {val, next}. Return true if the list contains a cycle. O(1) space required.
Ver solución
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next; // move 1 step
fast = fast.next.next; // move 2 steps
if (slow === fast) return true; // cycle!
}
return false;
}
// Floyd's Cycle Detection (tortoise & hare):
// If there's a cycle, fast will eventually lap slow.
// If no cycle, fast reaches null first.
// O(n) time, O(1) space — no extra Set needed.