Linked List Cycle II
Linked List Cycle II is LeetCode 142 (Medium). Given the head of a singly linked list, return the node where the cycle begins: the first node you reach a second time when you follow the next pointers. Return null if the list has no cycle.
- Do not change the list.
posin the examples only says where the last node links back to; it is not passed to your function.- The list has up to 10⁴ nodes, and the follow-up asks for O(1) extra memory.
- The number of the nodes in the list is in the range [0, 10⁴].
- -10⁵ <= Node.val <= 10⁵
- pos is -1 or a valid index in the linked-list.
Intuition
First find out whether there is a loop with the usual race: slow moves one node per round, fast moves two, and if they meet, both are inside the loop. The meeting node is usually not where the loop starts.
Counting steps fixes that. The distance from the head to the start equals the distance from the meeting node forward to the start, plus some whole laps of the loop. So put one pointer back on the head, leave the other on the meeting node, and move both one node at a time. They reach the start on the same step, and that is the first place they meet.
"Where does the repetition begin?" in a sequence of next steps, with O(1) memory, is Floyd's method with its second phase. Find the Duplicate Number uses the same two phases on an array.
Approach
Before reading on, run the fast and slow race by hand on a small list and mark where they meet. Then compare the distance from the head to the loop start with the distance from the meeting node to the start. Aim for O(n) time and O(1) space.
Two ways to solve it
Race slow and fast to a meeting node, then walk one pointer from the head and one from the meeting node until they meet.
- Memory: two pointers.
- Needs the proof to explain why it works.
The answer to the follow-up.
Walk the list and return the first node that is already in the set.
- Direct: the first repeated node is the start by definition.
- Cost: up to 10⁴ stored nodes.
The natural first idea.
Both take O(n) time. The two-phase pointer walk is shown first because it meets the O(1) memory follow-up; the visited-set version comes after the demo.
Race to a meeting node
Move slow one node and fast two nodes per round while fast and fast.next exist. If fast reaches the end, there is no loop, so return None. If slow is fast, both pointers are inside the loop.
Restart one pointer at the head
Set slow = head and leave fast on the meeting node. From here both move one node per round, because the distance argument below compares equal walks; at double speed the second pointer would overshoot.
Walk until they meet again
Advance both while slow is not fast, then return slow. The two walks reach the loop start on the same round and cannot meet earlier, because before that slow is still outside the loop while the other pointer is inside it.
Why the second meeting is the start
Call the head-to-start distance a, the start-to-meeting distance b, and the loop length L.
- At the meeting,
slowhas walkeda + bnodes andfasttwice as many. fast's extraa + bnodes were laps of the loop, soa + b = k · Lfor some whole numberk.- Walking
anodes from the meeting node endsb + a = k · Lpast the start, which is the start itself. The pointer from the head is there after the sameanodes.
Code in Python, C++ and Java
slow moves one node per round and fast two. The curved arrow is the link from the last node back to index 1, the node we want to return.slow walked a + b = 3 nodes and fast twice that; the extra 3 were whole laps of the loop of 3.slow moves one node per round and fast two. The curved arrow is the link from the last node back to index 5, the node we want to return.slow has not even reached the loop yet.slow has not even reached the loop yet.slow has not even reached the loop yet.slow has not even reached the loop yet.slow walked a + b = 6 nodes and fast twice that; the extra 6 were whole laps of the loop of 2.slow moves one node per round and fast two. fast stepped past the last node into null, so the list has an end.Set of visited nodes
Every node before the loop start is visited once, and the start is the first node the walk reaches twice. So the first node already in the set is the answer, and reaching None means there is no loop.
Common pitfalls
Returning the meeting node
if slow is fast:
return slowif slow is fast:
slow = head
while slow is not fast:
slow = slow.next
fast = fast.next
return slowOn [3, 2, 0, -4] with the tail linking to index 1, the pointers first meet on -4, but the loop starts at 2. The meeting only proves a loop exists; the second walk is what finds its start.
Keeping fast at two steps in the second walk
while slow is not fast:
slow = slow.next
fast = fast.next.nextwhile slow is not fast:
slow = slow.next
fast = fast.nextOn the same list, slow restarts at 3 and fast stays on -4. Moving fast two at a time, they meet on -4 again and the code returns -4 instead of 2, because the equal-distance argument needs both walks to cover the same number of nodes.
Edge cases
Here a = 0, so the meeting node is a whole number of laps from the head, which is the head itself. After the reset slow is fast already holds, and the head is returned without a single step.
fast or fast.next becomes None during the race, and the function returns None before the second walk starts.
Complexity
slow is caught before it finishes one lap of the loop. The second walk takes a rounds, fewer than n. Only two pointers are stored.Linked List Cycle II FAQ
How is this different from Linked List Cycle?
Linked List Cycle (LeetCode 141) returns only true or false, so it stops at the first meeting of the two pointers. This problem returns the node where the loop starts, which the meeting node usually is not, so it needs the second walk from the head and the distance argument behind it.
How do you find the length of the loop, or remove it?
For the length, stop at the meeting node and move one pointer round until it comes back, counting the steps. To remove the loop, find the start as above, then walk from the start to the node whose next is the start and set that next to None.