PIXELBANKv9.1.0
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 3→2→0→−43 \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: 3→2→0→−4→23 \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 locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.