Detect a loop in a linked list and how it works

Here we are going to use runner techniques, where there will be a two pointers slow and fast. Fast will going to take double steps then slow one, Lets see in below image.

As per the above image, you can see loops starts with Node (4), Lets assume distance from Node(1) to Node(3) is “m” and length of loop is “n“, Since we have two nodes (Slow and Fast), both will meet at some point in loop. Lets assume that point is at “k” distance from Node(4).

So now we have below three distances.

n = Length of cycle
m = Distance between first node of cycle (Node(4)) and head of linkedlist (Node(1))
k = Distance of point where slow and fast node meets.

Now lets assume distance traveled by Slow and Fast pointer as per below.

S = m+k+(R1)*n

– R1 is number of round made by Slow pointer in a loop before it meets to Fast pointer.

F = m+k+(R2)*n

– R2 is number of round made by Fast pointer in a loop before it meets to Slow pointer.