Linked List Cycle
Difficulty: Easy
Given the head of a linked list, decide whether it has a cycle: a node whose pointer loops back to an earlier node instead of eventually reaching null.
Return only true or false — you don't need to find where the cycle starts or how long it is.
Examples
Input: head = [3, 2, 0, -4], the last node connects back to the node with value 2
Output: true
Input: head = [1, 2], the last node connects back to the first node
Output: true
Input: head = [1]
Output: false
A single node whose pointer is null has nowhere to loop back to.
Constraints
The number of nodes is between 0 and 10^4.
-10^5 <= Node.val <= 10^5
Approach
The simple approach stores every visited node in a set. Landing on a node already in the set means there's a cycle; reaching null means there isn't. This costs extra memory for every node.
A better approach uses two pointers: a slow one that moves one node at a time and a fast one that moves two. With no cycle, the fast pointer reaches the end. With a cycle, the fast pointer enters the loop and closes the gap on the slow one until they meet on the same node. This needs no extra memory.
Solutions
Brute Force — Track Visited Nodes
Walk the list and store every node you see in a set. If the current node is already in the set, there's a cycle. If you reach null first, there isn't.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function hasCycle(head) {
const visited = new Set();
let node = head;
while (node !== null) {
if (visited.has(node)) return true;
visited.add(node);
node = node.next;
}
return false;
}Time: O(n) · Space: O(n)
Optimal — Floyd's Tortoise and Hare
Start two pointers at the head: slow moves one node per step, fast moves two. If fast (or its next node) hits null, the list ends and there's no cycle. If the two pointers land on the same node, fast has lapped slow inside a loop, which only happens when a cycle exists.
class ListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
function hasCycle(head) {
let slow = head;
let fast = head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}Time: O(n) · Space: O(1)