Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting a loop in a linked list - When would the pointers meet? How is the head of the loop found by intersection?

This question is related to: How to detect a loop in a linked list?

I have understood the solution but I didn't understand two statements I read in some book-

  1. If L is the length of the loop, n is the number of nodes,the slow and fast pointers will meet at n x L length - Is this correct? If not, when would they meet? Can someone please explain it in simple terms.

  2. To find the head of the loop, after the slow pointer and fast pointer meet, we move the slow pointer to the head and move both the pointers by 1 node until they intersect at the head of the loop - How does moving the slow pointer to the head and then moving both pointers by 1 node make them meet at the starting of the loop?

like image 898
user2441441 Avatar asked Dec 04 '25 04:12

user2441441


1 Answers

Before you reach the loop from the start you will need to traverse N - L nodes. (Where N is the total number of nodes except the initial node)

Let S and F be the number of nodes the slow and fast pointers traversed respectively.

For the two nodes to meet, 2 * S = F = S + x * L where x is an integer. Thus S would be L * ceiling( N / L ).

From the end if you move N - L nodes you will reach the start of the loop.

like image 140
M. Shaw Avatar answered Dec 06 '25 20:12

M. Shaw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!