Floyd's cycle-finding algorithm

From Quora

How does Floyd's cycle-finding algorithm work?

I understand that tortoise and hare's meeting concludes the existence of loop, but how does moving tortoise to beginning of linked list while keeping the hare at meeting place, followed by moving both one step at a time make them meet at starting point of cycle?

A lot of good perspectives.  The way I remember it is like Namrata's answer but, I think, a bit simpler without needing to explicitly manipulate any equations or worry about how many times the cycle is traversed.


We only need to consider two positions, s - the start of the cycle, and s+ x, where x is the offset from the cycle start where the two pointers meet.

When the slow pointer traveled s+ x, the fast one will have traveled an additional distance s+ x from the offset position x along the cycle.  This extra s+ x distance brought it back to the same position along the cycle (offset x). 

That means if moving a distance s+ x from that offset brings the pointer back to the offset x, then moving x less from that position, or s, will result in the pointer being at the start of the cycle - position s = offset 0. 

Therefore, starting the formerly-fast pointer from where they met (offset x along the cycle), and the formerly-slow pointer at the beginning, and moving both pointers at equal pace, after s iterations, the formerly-fast one will be at the cycle start s and, the formerly-slow one will also be at the cycle start s.




Fast pointer have to meet the slow one because their distance is s and the different of velocity is 1.
And when they meet, the slow pointer won't go further then (s+x) because s/1<(s+x)/1.(this circumstance will happen when the slow one get into the circle and the fast one is in the x)

你可能感兴趣的:(LeetCode)