I understand the concept of Floyd's algorithm for cycle detection. It concludes that if the Tortoise travels twice as fast as the Hare, and if the Tortoise has a head start of k meters in a loop, the Tortoise and the Hare will meet k meters before the loop.
In the case of singly linkedlist, you have pointer A travelling twice as fast as pointer B. This means that if it takes pointer B k-steps to reach the entry point of the loop(which we dont know where it is yet), pointer A will already have a head start of k nodes inside the loop. Therefore, two pointers will meet k nodes before the entry point of the loop. Thus, if we move pointer B back to the head pointer and keep pointer A at the meeting point(now both pointers are k nodes away from the entry point), and move both at the same pace, they will meet at the entry point of the loop.
How can you prove that the algorithm will work in the following boundary cases?
- A linkedlist where the last node loop back to the head. In this case, what will the head start value, k, be?
- A super long linkedlist, 1000 nodes, and has a small loop at the end, 3 nodes. Pointer A will have a head start of 1000, which means by the time pointer B reaches the entry point of the loop, A will already have looped many times.
- What if there is a loop of 1 node?
This is not homework. I was told by an interviewer that this algorithm won't work if I have a small loop. He didn't explain why.