Easy

Quiz

#141 Linked List Cycle

APPROACH

Given head, the head of a linked list, determine whether the list contains a cycle.

A cycle exists if some node can be reached again by repeatedly following next pointers. The variable pos (not passed to your function) indicates which node the tail's next connects back to.

Return true if a cycle exists, otherwise false.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
1 of 4
1:00

What is the optimal approach for this problem?