PIXELBANKv8.2.1
Menu

Linked List Cycle Detection

Given a list and a pos (0-indexed position where the tail connects to form a cycle), return True if there is a cycle, False otherwise. pos = -1 means no cycle.

Example:

Input:
3,2,0,-4
1
Output:
True
Reasoning:
  • The input list is created as 32043 \rightarrow 2 \rightarrow 0 \rightarrow -4, with each number representing a node's value.
  • The input pos = 1 indicates that the tail of the list connects to the node at index 1, forming a cycle: 320423 \rightarrow 2 \rightarrow 0 \rightarrow -4 \rightarrow 2.
  • We can detect this cycle using the two-pointer technique, where one pointer moves twice as fast as the other, and if there is a cycle, these two pointers will eventually meet.
  • Since the pointers meet at the node with value 2, we conclude that a cycle exists in the list.
  • The final output is therefore True.

Constraints:

  • 0 <= number of nodes <= 10^4
  • -10^5 <= Node.val <= 10^5
  • pos is -1 or a valid index
Editor

Test Results

0/0
Run code to see test results.