376. Find Length of Loop in Linked List

MediumLinked ListFloyd's Cycle DetectionTwo PointersLinked List

Given a linked list, return the number of nodes in its loop, or 0 if there is no loop. The list is given as an array of values plus pos, the 0-based index that the tail connects to (pos = -1 means no loop). Input: '[list], pos'.

Input: '[list], pos'.

Output: Integer — loop length, or 0.

Examples

Example 1
Input: [1,2,3,4,5], 1
Output: 4
Explanation: Loop covers indices 1..4.
Example 2
Input: [1,2,3,4], 0
Output: 4
Explanation: Whole list loops.
Example 3
Input: [1], -1
Output: 0
Explanation: No loop.

Constraints

Asked by

AmazonMicrosoftGoogleAdobeFlipkart
Solve this problem in the editor →