Task example: Linked List Cycle II

Return the original node where the next links begin to repeat. If the chain ends at None, return None. Do not change any node values or links.

Example 1
Input
head = [3,2,0,-4], pos = 1
Output
node 1 (val=2)

Values describe the nodes. pos is the zero-based index that the tail connects to; -1 means no cycle. The editor builds that connection and supplies ListNode with val and next. Your function receives only head and must return a node, not its value or index.

LeetCode 142
01 / Visited-node set - extra space

Visited-node set: video explanation

head = [3,2,0,-4], pos = 1
result = node 1 (val=2)

Prefer reading? Follow the steps below.

  1. Start at head with an empty set. Check whether the current node object is already in the set before adding it.
  2. If a node is already present, return it: the first repeated object is the cycle entry. Otherwise add it and follow next. Equal values in different nodes do not prove a cycle.
  3. If current reaches None, return None. The set stores references; the original list stays unchanged.

Time complexity · O(N)

Each distinct node is added once before a repeat or None. With average O(1) hash-set operations, time complexity is O(N). N counts distinct nodes.

Space complexity · O(N)

The set may hold all N node references, so extra space is O(N).

PYTHONLive code trace
02 / Floyd's two pointers - optimal space

Floyd's two pointers: video explanation

head = [3,2,0,-4], pos = 1
result = node 1 (val=2)

Prefer reading? Follow the steps below.

  1. Phase 1: start slow and fast at head. Move slow one link and fast two links, then compare their identities. If fast or fast.next is None, there is no cycle. A meeting inside the cycle is not necessarily its entry.
  2. Phase 2: after a meeting, put entry at head and leave slow at the meeting node. Move both one link at a time. When they reference the same object, return entry.
  3. Why it works: let A be the head-to-entry distance, B the entry-to-meeting distance, and C the cycle length. At the first meeting, A + B is a multiple of C. Moving A more steps from the meeting reaches the entry, after any full laps. The pointer from head reaches it in the same A steps.

Both approaches take linear time. Floyd's algorithm removes the growing visited set and uses constant extra space. Neither approach changes the list.

Time complexity · O(N)

Detection and entry search together take O(N) time, where N is the number of distinct nodes, including the cycle.

Space complexity · O(1)

Only slow, fast, and entry references are stored: O(1) extra space.

PYTHONLive code trace

Linked List Cycle II · The task

Close or press Esc to return to your place. The task button stays pinned while you explore the solutions.