2

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 ?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Devender Goyal
  • 1,450
  • 3
  • 18
  • 26
  • Good question regardless, first question that entered my mind when I saw this algorithm. Could there be a loop size and fast pointer step size that would result in the fast pointer and slow pointers always missing each other? – AnthonyVO Jul 18 '19 at 00:05
  • e.g. Loop = 6, Fast = 3, Slow 1. Start the Slow pointer right behind the Fast pointer. – AnthonyVO Jul 18 '19 at 00:31

3 Answers3

2

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.

interjay
  • 107,303
  • 21
  • 270
  • 254
0

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.

A. K.
  • 34,395
  • 15
  • 52
  • 89
0

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.

harshitpthk
  • 4,058
  • 2
  • 24
  • 32