简体   繁体   中英

Floyd loop detection algorithm with different step size

In the Floyd loop detection algorithm in linked list ,we generally increment slow pointer by 1 unit and fast pointer by 2 unit. What are the other values that we can use for incrementing the slow and fast pointer and how do they change the complexity of algorithm ?

The two pointers will always meet, regardless of speeds or loop size.

Using the following values:

  • a and b : The number of steps taken by each pointer for each iteration.
  • m : The number of nodes in the loop.

After i iterations, the two pointers will have taken ai and bi steps. They will be at the same node if i is large enough that both pointers are inside the loop, and:

ai = bi (mod m)

which is the same as:

(a-b)i = 0 (mod m)

This will be true for a value of i which is a multiple of m , and is large enough. Such a value will always exist so the pointers will always meet.

Larger values of a and b will increase the number of steps taken per iteration, but if they are both constants then the complexity will still be linear.

I think the step size does not matter. As long as slow < fast the two would meet if there is a cycle in the list.

The only difference would be that in each iteration the number of steps taken by each pointer would vary.

well i understood it in an argumentative way with use of some basics maths. imagine a linked list with a loop,both the slow pointer and the fast pointer starts moving. Let T be the point where the loop starts or the node where the list connects itself. when the slow pointer reaches this node the fast pointer would now be inside the loop. so hence now imagine this loop like clock having an hour hand and a minute hand , the two pointers will meet irrespective of their speed on the common multiples of their speeds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM