IBM Interview Question
Developer Program EngineersTeam: ISL
Country: India
Interview Type: In-Person
One way to prove it mathematically:
Assume there is a loop in the list, we have:
a = index of pointer P
b = index of pointer Q
start = index of the loop's starting point
len = loop's length (how many elements in the loop)
t = how many times we have moved pointers of P and Q since both of them are in the loop
We get:
a = start + t % len
b = start + 2t % len
So the distance between P and Q will be:
distance = | a - b | = | t % len |
When there is a loop, it is always possible that
t % len == 0
When there is not a loop, distance will never be 0.
So this approach works.
There is the no loop in your example :). I explained this, Interviewer was expecting some other answer.
let this be address of list
100->200->300->400->500->600->300(loop back to 3rd node)
let two pointers p and q
initailly p,q are @ 100
then p @200
q @300
then p @300
q @500
then p @400
q @300
then p @500
q @500
slow n fast pointer will point to node whoose
next node is making loop
slow move with x speed
fast will move with 2x speed
they will meet at point where actually loop
tend to start
but there is a assumption that head node must not
create a loop.
100->200->300->400->500->600->100(loop back at 1st node)
then above calculations fails
Algorithm is here :
Complexity : O(Length of linked list)
- sonesh March 05, 2013Prove is here :
It is easy to see that if the linked list has a loop then after some time both the pointer will be in the loop.
Consider the time when they are in the loop. Now let First pointer is at Ith node, and Second pointer is at Jth node in linked list. Lets assume that node at Ith place is faster one. So Ith node require J-I+1 move in order to reach to Jth node, and we know that First pointer is moving 1 node relative to second one.which mean it move one node nearer to second in every step. so in J-I+1 step's it will reaches to node second. Hence proved.