instagram

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.

Since Fast pointer is twice faster than Slow pointer.

F = 2S
F = 2( m+k+(R1)*n )
m+k+(R2)*n = 2( m+k+(R1)*n )
m+k = (R2-2R1) n (This is IMP Step)

As per above equation m+k is equal to some number of loops.

Lets assume (R2-2R1) = 1.
m+k = (R2-2R1) n
m+k = (1)n

Here m+k is equal to one entire loop.

It means if we travel m+k is equivalent to travel one entire loop , Here one entire loop means start from Node(4) and end to Node(4).

Now we are going to move slow node at first position and now move fast and slow both node at same speed.

Here distance travelled by slow node is as per below.

S = m

At same time distance travelled by Fast node is also m but fast node started from k distance so total will be k+m

F = m+k

so as per above m+k is one entire loop (n). [m+k = (1)n] . So because of this when Slow will reach to Node(4) at same time Fast will finished its one loop and will reach to same Node(4)

Share