MediumLinked ListTwo PointersHash Table

Linked List Cycle II

1 approach, code in every language

Problem description

Given the head of a singly linked list, return the node where a cycle begins. If the list has no cycle, return null.

A cycle occurs when the tail links back to an earlier node instead of terminating. That entry point is what you must locate. You should not modify the list, and ideally you solve it using only constant extra space.

Example 1

Input: head = [3,2,0,-4], pos = 1

Output: Node at index 1 (value 2)

The tail loops back to the node with value 2, so the cycle begins there.

Example 2

Input: head = [1,2], pos = 0

Output: Node at index 0 (value 1)

The second node points back to the head, making the head the cycle entry.

Constraints

  • The number of nodes is in the range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • pos is -1 (no cycle) or a valid 0-based index into the list.

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free