LeetCode #142 Medium

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.
  • pos in 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.
Constraints
  • 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.
linked listtwo pointersfloyd
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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, slow has walked a + b nodes and fast twice as many.
  • fast's extra a + b nodes were laps of the loop, so a + b = k · L for some whole number k.
  • Walking a nodes from the meeting node ends b + a = k · L past the start, which is the start itself. The pointer from the head is there after the same a nodes.
04

Code in Python, C++ and Java

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
▶6 slow = fast = head
▶7 while fast and fast.next:
▶8 slow = slow.next
▶9 fast = fast.next.next
▶10 if slow is fast:
▶11 slow = head
▶12 while slow is not fast:
▶13 slow = slow.next
▶14 fast = fast.next
▶15 return slow
▶16 return None
back to index 1, loop of 3302102-43slowfastphase 1: both start on 3
slow3
fast3
Phase 1 only answers is there a loop? 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.
back to index 1, loop of 3302102-43slowfastround 1: slow → 2, fast → 0
slow2one step
fast0two steps
Different nodes, so the race goes on.
back to index 1, loop of 3302102-43slowfastround 2: slow → 0, fast → 2
slow0one step
fast2two steps
Different nodes, so the race goes on.
back to index 1, loop of 3302102-43slowfasta = 1b = 2round 3: both on -4 → a loop, but is this its start?
slow-4
fast-4
a + b31 lap of 3
They meet on -4 after 3 rounds, so there is a loop. The loop starts at index 1, 2 nodes earlier, so the meeting node is not the answer. slow walked a + b = 3 nodes and fast twice that; the extra 3 were whole laps of the loop of 3.
back to index 1, loop of 3302102-43from headfrom meeta = 1b = 2phase 2: one pointer back to the head, both now move 1
slow3head
fast-4meeting node
Since a + b is a whole number of laps, walking a = 1 nodes from the meeting node lands on the loop start, and so does walking a nodes from the head. So restart one pointer at the head and move both one node per round.
back to index 1, loop of 3302102-43from headfrom meetphase 2, round 1: 2 and 2 → same node
slow2
fast2
After exactly a = 1 rounds both pointers stand on 2, the node at index 1.
back to index 1, loop of 3302102-43from headfrom meetreturn 2, the start of the loop
resultnode 2 (index 1)
The walks met on 2, the first node reached twice from the head, so it is the start of the loop. Two pointers were all the memory used.
05

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.

▶1from typing import Optional
▶2 
▶3 
▶4class Solution:
▶5 def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
▶6 seen = set()
▶7 node = head
▶8 while node:
▶9 if node in seen:
▶10 return node
▶11 seen.add(node)
▶12 node = node.next
▶13 return None
06

Common pitfalls

Returning the meeting node

✗ Wrong
if slow is fast:
    return slow
✓ Right
if slow is fast:
    slow = head
    while slow is not fast:
        slow = slow.next
        fast = fast.next
    return slow

On [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

✗ Wrong
while slow is not fast:
    slow = slow.next
    fast = fast.next.next
✓ Right
while slow is not fast:
    slow = slow.next
    fast = fast.next

On 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.

07

Edge cases

The loop starts at the head

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.

No loop

fast or fast.next becomes None during the race, and the function returns None before the second walk starts.

08

Complexity

Time
O(n)
Space
O(1)
The race takes at most n rounds, since 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.
09

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.