Linked List Cycle II (LeetCode 142): Solution and Explanation
Given the head of a singly linked list, return the node where a cycle begins, or None if the list ends normally. You may not modify the list, and the follow-up asks for constant extra memory.
Watch it run step by step
Try your own input and write the code →Intuition
The simplest correct approach stores every visited node in a hash set. Walk the list, and the first node you see a second time is the start of the cycle, because it is the first node reachable from two directions. That is O(n) time but also O(n) memory, and the follow-up asks you to do better.
Floyd's tortoise and hare algorithm detects a cycle in constant space. Move slow one step and fast two steps at a time. If the list ends, there is no cycle. If there is a cycle, fast gains one node per step on slow once both are inside the loop, so it must eventually land on the same node. Detecting the cycle is the easy half; the clever part is locating its entrance.
Let a be the distance from the head to the cycle entrance, b the distance from the entrance to the meeting point, and c the cycle length. When they meet, slow has walked a + b steps and fast has walked twice that. The extra a + b steps fast took are whole laps, so a + b is a multiple of c. Rearranged, a equals some number of laps minus b, which is exactly the distance from the meeting point forward to the entrance (plus whole laps). So if you put one pointer back at the head and move both one step at a time, they arrive at the entrance together.
Approach: Floyd's cycle detection
- Start both
slowandfastathead. - While
fastandfast.nextexist, moveslowone node andfasttwo nodes. - If they ever point to the same node, a cycle exists and they are at the meeting point.
- Reset
slowtohead, keepfastat the meeting point, and advance both one node at a time until they are equal. - Return the node where they meet, which is the start of the cycle.
- If the outer loop ends because
fastreached the end, return None since there is no cycle.
Step-by-step example
head = [3, 2, 0, -4], tail connects to the node with value 2 (index 1)
- Both pointers start at 3. After one step,
slowis at 2 andfastis at 0. - After the second step,
slowis at 0 andfasthas moved from 0 to -4 and then back to 2. - After the third step,
slowis at -4 andfastmoves from 2 to 0 to -4. They meet at -4. - Reset
slowto 3 whilefaststays at -4. One step later,slowis at 2 andfastfollows the back edge to 2. - They are equal, so the function returns the node with value 2. Here
a = 1,b = 2andc = 3, and indeeda + b = 3is one full lap.
Code: Python, Java, C++
1class Solution:
2 def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
3 slow = fast = head
4 while fast and fast.next:
5 slow = slow.next
6 fast = fast.next.next
7 if slow == fast:
8 slow = head
9 while slow != fast:
10 slow = slow.next
11 fast = fast.next
12 return slow
13 return None1public class Solution {
2 public ListNode detectCycle(ListNode head) {
3 ListNode slow = head, fast = head;
4 while (fast != null && fast.next != null) {
5 slow = slow.next;
6 fast = fast.next.next;
7 if (slow == fast) {
8 slow = head;
9 while (slow != fast) {
10 slow = slow.next;
11 fast = fast.next;
12 }
13 return slow;
14 }
15 }
16 return null;
17 }
18}1class Solution {
2public:
3 ListNode *detectCycle(ListNode *head) {
4 ListNode *slow = head, *fast = head;
5 while (fast && fast->next) {
6 slow = slow->next;
7 fast = fast->next->next;
8 if (slow == fast) {
9 slow = head;
10 while (slow != fast) {
11 slow = slow->next;
12 fast = fast->next;
13 }
14 return slow;
15 }
16 }
17 return nullptr;
18 }
19};Time and space complexity
O(n)
Before meeting, slow takes at most about n steps because fast closes the gap within one lap of slow entering the cycle. The second phase takes a steps, which is at most n.
O(1)
Only two pointers are used, and the list is not modified.
Other approaches
Hash set of visited nodes (time O(n), space O(n))
Walk the list and add each node to a set. The first node already in the set is the cycle start. It is easy to write and explain, but it stores up to n node references.
Common mistakes
- Checking
slow == fastbefore moving them. Both start athead, so the check succeeds immediately and returns the head even when there is no cycle. - Resetting
fastinstead ofslowand then still movingfasttwo steps at a time in the second phase. Both pointers must move one step in the entrance search. - Only checking
fastfor None but notfast.next, which crashes on lists with an even number of nodes and no cycle. - Comparing node values instead of node identity. Lists can contain duplicate values, so you must compare the node objects themselves.
Frequently asked questions
Why does resetting one pointer to the head find the cycle start?
At the meeting point, the distance from the head to the entrance equals the distance from the meeting point to the entrance, modulo the cycle length. Moving both pointers at the same speed therefore brings them to the entrance at the same moment.
Why must the fast pointer meet the slow pointer inside the cycle?
Once both are in the loop, the gap between them shrinks by exactly one node each step. A gap that shrinks by one cannot jump over zero, so they must land on the same node.
Can Linked List Cycle II be solved without extra memory?
Yes, Floyd's algorithm uses only two pointers. The hash set approach is simpler but uses O(n) memory.