Linked List Cycle II

IF
AlgoAxiomStaff Engineers
JSTS
Medium20 mins

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

A cycle exists if some node in the list can be reached again by continuously following the next pointer. Internally, pos denotes the index of the node that the tail's next pointer connects to (0-indexed). If pos is -1, there is no cycle. Note that pos is not passed as a parameter — it is only used to build the linked list for testing.

Return the value of the node where the cycle starts, or "null" if there is no cycle.

Examples

Example 1:

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

Output: 2

Explanation: There is a cycle where the tail node (-4) connects back to the node at index 1 (value 2). The cycle starts at the node with value 2.

Example 2:

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

Output: 1

Explanation: There is a cycle where the tail node (2) connects back to the node at index 0 (value 1). The cycle starts at the node with value 1.

Example 3:

Input: head = [1], pos = -1

Output: null

Explanation: There is no cycle in the linked list.

Constraints

  • The number of 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
Source: Fast and Slow Pointers pattern — AlgoAxiom
JavaScript
Test Case 1
root = [1, 2, 3]
Test Case 2
root = [1, 2, 3, 4, 5]
Idle