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

后端 未结 8 494
眼角桃花
眼角桃花 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:22

    Say we use two references Rp and Rq which take p and q steps in each iteration; p > q. In the Floyd's algorithm, p = 2, q = 1.

    We know that after certain iterations, both Rp and Rq will be at some elements of the loop. Then, say Rp is ahead of Rq by x steps. That is, starting at the element of Rq, we can take x steps to reach the element of Rp.

    Say, the loop has n elements. After t further iterations, Rp will be ahead of Rq by (x + (p-q)*t) steps. So, they can meet after t iterations only if:

    • n divides (x + (p-q)*t)

    Which can be written as:

    • (p−q)*t ≡ (−x) (mod n)

    Due to modular arithmetic, this is possible only if: GCD(p−q, n) | x.

    But we do not know x. Though, if the GCD is 1, it will divide any x. To make the GCD as 1:

    • if n is not known, choose any p and q such that (p-q) = 1. Floyd's algorithm does have p-q = 2-1 = 1.
    • if n is known, choose any p and q such that (p-q) is coprime with n.

    There is some discussion around evaluating general p and q for this algorithm in this article.

    0 讨论(0)
  • 2020-12-04 06:28

    If the linked list has a loop then a fast pointer with increment of 2 will work better then say increment of 3 or 4 or more because it ensures that once we are inside the loop the pointers will surely collide and there will be no overtaking.

    For example if we take increment of 3 and inside the loop lets assume

    fast pointer --> i  
    slow         --> i+1 
    the next iteration
    fast pointer --> i+3  
    slow         --> i+2
    

    whereas such case will never happen with increment of 2.

    Also if you are really unlucky then you may end up in a situation where loop length is L and you are incrementing the fast pointer by L+1. Then you will be stuck infinitely since the difference of the movement fast and slow pointer will always be L.

    I hope I made myself clear.

    0 讨论(0)
提交回复
热议问题