oneby7

Linked Lists Fast and slow pointers

296. Length of the Loop in a Linked List

Easy

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:

3head-81-8627

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

3-81-8627

Input: head = [3, -8, 1, -8, 6, 2, 7], pos = 4

Output: 3

Explanation: 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

-3-3-3-3

Input: head = [-3, -3, -3, -3], pos = 0

Output: 4

Explanation: 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

60-4

Input: head = [6, 0, -4], pos = -1

Output: 0

Explanation: 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.

head = [4, 9, 4, 1, 9], pos = 1

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • -1 ≤ pos ≤ 105 − 1
  • A pos outside 0 … 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.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.