📘
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→−4, with each number representing a node's value.
- The input
pos = 1indicates that the tail of the list connects to the node at index 1, forming a cycle: 3→2→0→−4→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
Python 3.13.1
Test Results
0/0Run code to see test results.