MentorNode
Start free
Fast & Slow Pointers/easy

Linked List Cycle Detection

fast-slow-pointerslinked-list-cycle

Linked List Cycle Detection

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

A cycle exists if there is some node in the list that can be reached again by continuously following the next pointer.

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

(For array simulation in tests, inputs are given as array of values and pos index).

Example 1

Input: values = [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).

Constraints

  • Number of nodes is in range [0, 10^4].
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index.

Loading workspace editor...
Ready to run
Input:
{
  "values": [
    3,
    2,
    0,
    -4
  ],
  "pos": 1
}
Expected Output:
true