Linked Lists Fast and slow pointers
296. Length of the Loop in a Linked List
You are given head, the first node of a singly linked list. The list may have a loop: the last node's
next, instead of being null, may point back to an earlier node or to the last node itself. Return the
number of nodes in the loop, or 0 if the list has no loop.
The loop is the set of nodes that a walk from the head passes again and again. The nodes before the first of them are not part of it. In the list below, the last node points back to the node at index 4, so the loop is the three nodes holding 6, 2 and 7:
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The
second input, pos, says how the loop is closed: the last node's next points to the node at index pos,
counting from 0 at the head. pos = -1 means the last node's next is null. Your function gets only head;
it never sees pos.
Example 1
Input: head = [3, -8, 1, -8, 6, 2, 7], pos = 4
3Explanation: This is the list in the picture. A walk from the head passes 3, -8, 1 and -8 once, then goes round the nodes holding 6, 2 and 7 forever. The two nodes holding -8 are different nodes, and neither is in the loop.
Example 2
Input: head = [-3, -3, -3, -3], pos = 0
4Explanation: The last node points back to the head, so every node is in the loop. All four hold -3; only the nodes themselves tell them apart.
Example 3
Input: head = [6, 0, -4], pos = -1
0Explanation: The last node's next is null, so the walk ends and the list has no loop.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109-1 ≤ pos ≤ 105 − 1- A
posoutside0 … n − 1, where n is the number of nodes, means the list has no loop.
Clarifying questions
What you would ask an interviewer before writing any code.