Why increase pointer by two while finding loop in linked list, why not 3,4,5?

后端 未结 8 515
眼角桃花
眼角桃花 2020-12-04 05:29

I had a look at question already which talk about algorithm to find loop in a linked list. I have read Floyd\'s cycle-finding algorithm solution, mentioned at lot of places

8条回答
  •  清歌不尽
    2020-12-04 06:10

    If there is a loop (of n nodes), then once a pointer has entered the loop it will remain there forever; so we can move forward in time until both pointers are in the loop. From here on the pointers can be represented by integers modulo n with initial values a and b. The condition for them to meet after t steps is then

    a+t≡b+2t mod n which has solution t=a−b mod n.

    This will work so long as the difference between the speeds shares no prime factors with n.

    Reference https://math.stackexchange.com/questions/412876/proof-of-the-2-pointer-method-for-finding-a-linked-list-loop

    The single restriction on speeds is that their difference should be co-prime with the loop's length.

提交回复
热议问题