Given the head of a singly linked list, determine whether the list has a cycle in it.
If a cycle exists, return the length of the cycle, which is the number of nodes in the loop. If there is no cycle, return 0.
A linked list has a cycle when some node in it can be reached again by repeatedly following next pointers.
Function Signature
from typing import Optional
class ListNode:
def __init__(self, val: int = 0, next: "Optional[ListNode]" = None):
self.val = val
self.next = next
def find_loop_length(head: Optional[ListNode]) -> int:
...
Rules
-
Each test writes the list as
head = [v0, v1, ..., vk]
plus an integer
pos
. The harness creates one node per value, links the nodes in order, and points the tail's
next
at the node with zero-based index
pos
. When
pos = -1
, the tail's
next
is
None
.
-
pos
is not passed to the function. The function receives only the first node, or
None
for an empty list.
-
Node values can repeat. Two nodes with the same value are still different nodes.
-
An empty list has no cycle, so the answer is
0
. A single node whose
next
points to itself is a cycle of length
1
.
Constraints
-
0 <= number of nodes <= 10^4
-
-10^5 <= Node.val <= 10^5
-
pos
is
-1
or a valid index in the linked list
Examples
Input: head = [3,2,0,-4], pos = 1
Output: 3
The tail (value -4) links back to index 1 (value 2), so the loop is 2 -> 0 -> -4 -> 2. It contains 3 nodes.
Input: head = [1,2], pos = 0
Output: 2
The tail links back to the head, so the loop is 1 -> 2 -> 1 and both nodes are in it.
Input: head = [5,8,1], pos = -1
Output: 0
The last node's next is None, so following the pointers reaches the end of the list and there is no cycle.