Linked List Cycle
Difficulty: Easy · Pattern: Linked List · LeetCode #141
Return true if the linked list contains a cycle (following next pointers eventually revisits a node), otherwise false. Can you do it with O(1) memory?
In the tests, the input is [values, pos], where pos is the index the tail connects back to (−1 = no cycle). Your function receives only the head.
Examples
values = [3, 2, 0, -4], pos = 1 → true (tail → node at index 1)
values = [1, 2], pos = −1 → falseHints
- A set of visited nodes works but costs O(n) memory.
- Move one pointer 1 step and another 2 steps. If there's a cycle, can the fast one avoid the slow one forever?
Approach
Floyd's algorithm: slow advances 1 node per step, fast advances 2. If the list ends (fast or fast.next is null), there's no cycle. If there is a cycle, once both are inside it the gap between them shrinks by exactly 1 each step, so fast must land on slow. Step through it with the visualizer above.
Bonus: to find where the cycle starts (LeetCode 142), reset one pointer to the head after they meet and advance both one step at a time; they meet at the cycle entrance.
Complexity
Time: O(n). Space: O(1).
Python solution
def hasCycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return FalseJavaScript solution
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;
}