Detect a Loop in a Linked List

Implement hasLoop

Given the head of a singly linked list, return true if the list contains a cycle — some node's next pointer leads back to an earlier node instead of eventually reaching null. Since a cyclic list can never be fully printed or walked to completion, this test's inputs are described as (values, pos): build a normal list from the values, then point the last node's next at the node located at index pos (0-indexed). pos = -1 means no cycle at all. The optimal solution — Floyd's Cycle DetectionFloyd's Cycle DetectionAlso called the "tortoise and hare" algorithm. Two pointers move through the list at different speeds (1 step and 2 steps). If a cycle exists, both get trapped inside it and are guaranteed to eventually land on the same node — since the faster one gains exactly one node on the slower one every step. — detects this in O(1) extra space, without ever storing a single visited node.

Example 1:

Input: head = {"vals":[3,2,0,-4],"pos":1}

Output: true

Example 2:

Input: head = {"vals":[1,2],"pos":0}

Output: true

Example 3:

Input: head = {"vals":[1],"pos":-1}

Output: false

+ 5 hidden test cases run on Submit.

Constraints:

  • 0 ≤ number of nodes in head ≤ 10⁴
  • -10⁹ ≤ node value ≤ 10⁹
  • A cyclic test list is described as (vals, pos) — the last node's next points back to index pos (0-indexed); pos = -1 means no cycle

head =

{"vals":[3,2,0,-4],"pos":1}