Linked List Cycle II (LeetCode 142): Solution and Explanation

Medium
Hash Table
Linked List
Two Pointers

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Start both slow and fast at head.
  2. While fast and fast.next exist, move slow one node and fast two nodes.
  3. If they ever point to the same node, a cycle exists and they are at the meeting point.
  4. Reset slow to head, keep fast at the meeting point, and advance both one node at a time until they are equal.
  5. Return the node where they meet, which is the start of the cycle.
  6. If the outer loop ends because fast reached 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)
  1. Both pointers start at 3. After one step, slow is at 2 and fast is at 0.
  2. After the second step, slow is at 0 and fast has moved from 0 to -4 and then back to 2.
  3. After the third step, slow is at -4 and fast moves from 2 to 0 to -4. They meet at -4.
  4. Reset slow to 3 while fast stays at -4. One step later, slow is at 2 and fast follows the back edge to 2.
  5. They are equal, so the function returns the node with value 2. Here a = 1, b = 2 and c = 3, and indeed a + b = 3 is 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 None

Time and space complexity

Time

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.

Space

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 == fast before moving them. Both start at head, so the check succeeds immediately and returns the head even when there is no cycle.
  • Resetting fast instead of slow and then still moving fast two steps at a time in the second phase. Both pointers must move one step in the entrance search.
  • Only checking fast for None but not fast.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.