Linked List Cycle II
Find the node where a linked list's cycle begins, or null if there is none, with O(1) extra memory.
The problem
You get the head of a singly linked list that may contain a cycle. Return the node where the cycle begins, which is the node the tail links back to, or null if the list has no cycle, and leave the list unchanged. In the examples, pos is the index the tail links back to (-1 means no cycle), and the answer is shown as the index of the returned node.
Input head = [12, 4, 9, 15, 6], pos = 1
Output index 1 (the node with value 4)
The last node (6) links back to the 4, so the loop starts there.
Input head = [3, 1], pos = -1
Output null
The list ends after 1, so there is no cycle.
Key constraint: Use O(1) extra memory and don't change the list.
How to spot the pattern
- It is Linked List Cycle, but you need the exact entry point of the loop.
- A hash set would work, but the follow-up asks for constant memory.
The idea
Run slow and fast pointers until they meet inside the loop; if fast reaches the end, there is no cycle. A little algebra shows that the distance from the head to the cycle's start equals the distance from the meeting point forward to the start, give or take whole laps. So restart one pointer at the head and move both one step at a time: they meet exactly at the first node of the cycle.
Brute force: Walk the list and store each node in a hash set; the first node you see twice is the start, at the cost of O(n) extra memory.
Step by step
- 1Move
slowone step andfasttwo steps until they meet orfastreaches the end. - 2If
fastreached the end, returnnull. - 3Put a new pointer at
headand keepslowat the meeting point. - 4Move both one step at a time; the node where they meet is the start of the cycle.
See the pattern move
The fast and slow pointers pattern on a small example. Step through it, or press play.
Code
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
# The head and the meeting point are the same distance from the
# cycle's start, so walk one step at a time from both.
finder = head
while finder is not slow:
finder = finder.next
slow = slow.next
return finder
return NoneComplexity
Time
O(n)
Space
O(1)
Each phase walks the list a small number of times and keeps only a few pointers.
Watch out for
- Returning the meeting point itself: it is somewhere inside the loop, not necessarily its start.
- Comparing node values instead of nodes, which breaks as soon as values repeat.
- Forgetting the no-cycle case, which has to return
null.
Follow-up questions
Why does restarting one pointer at the head work?
Say the cycle starts a steps from the head, they meet b steps into the loop, and the loop has length c. Fast walked twice as far as slow, so a + b is a multiple of c; walking a more steps from the meeting point therefore lands exactly on the start.
Where else does this trick show up?
Find the Duplicate Number treats the array as a linked list (index i points to nums[i]) and uses the same two phases.
In Hinglish
Pehle slow aur fast ko milne do. Phir ek pointer head se chalao aur doosra milne wali jagah se, dono ek-ek step; jahan milein wahi cycle ka start hai.