Tensorum
LeetCode 142 · Fast & Slow Pointers

Linked List Cycle II

LeetCode 142 · Medium · solution, intuition & step-by-step walkthrough

Meet, reset one to head, step together → cycle start.

MediumHash TableLinked ListTwo PointersFloyd's Cycle Finding Algorithm
72 msruntime · beats 7%
53.7 MBmemory · beats 100%
1approach
7accepted runs · last 15 Dec 2024

This is how I solved Linked List Cycle II (LeetCode 142), a medium problem from the Fast & Slow Pointers pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.

Approach

  1. 1

    Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle).

  2. 2

    Phase 2: fast = head.

  3. 3

    Advance both by one until they meet; return that node.

How I solved it

Floyd two-phasePythonO(n) time · O(1) space
class Solution:
    def detectCycle(self, head):
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                break
        if fast is None or fast.next is None:
            return None
        fast = head
        while slow != fast:
            slow = slow.next
            fast = fast.next
        return slow
Loading the step-through…

Linked List Cycle II — FAQ

What is the intuition behind Linked List Cycle II?

After slow and fast meet inside the loop, the distance from the head to the loop entrance equals the distance from the meeting point to the entrance (going around). Restart one pointer from the head and step both by one: they meet exactly at the entrance.

How do you solve Linked List Cycle II (LeetCode 142)?

1. Phase 1: Floyd until slow == fast (or fast reaches the end → no cycle). 2. Phase 2: fast = head. 3. Advance both by one until they meet; return that node.

What is the time and space complexity of Linked List Cycle II?

Time: O(n). Space: O(1). (Accepted approach: Floyd two-phase.)

What are common mistakes in Linked List Cycle II?

Return null when phase 1 ends without meeting.