Find loop length in a cyclic/circular linked list
Input :
A linked list
Output:
An integer

This post is a follow-up of
- JavaScript Linked List Example
- Detect a loop in cycliccircular linked list.
I recommend reading those posts first, as the following code uses the methods from it.
Logic:
- Find the loop, using the same logic Detect a loop in cycliccircular linked list.
- Move
p2
one step at a time keepingp1
at a fixed location. - Use a
loopLength
variable to keep track of loop length. - When
p1 === p2
return the loopLength.
Watch the following video to understand the Floyd's cycle-finding algorithm!