Linked List Cycle

IF
AlgoAxiomStaff Engineers
JSTS
Easy20 mins

Given the head of a linked list, determine if the linked list has a cycle in it.

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. Note that pos is not passed as a parameter — it is only used to build the linked list for testing.

Return true if there is a cycle in the linked list. Otherwise, return false.

Examples

Example 1:

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

Output: true

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

Example 2:

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

Output: true

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

Example 3:

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

Output: false

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