Interview Question
Country: United States
A little improvement in step 2
-Once we find the starting of the loop, we can just measure the length of the 2 lists till we encounter that specific node (the starting node, we don't need to enter the loop).
-Calculate diff = length1 - length2
-Move (diff) no. of nodes forward in the longer list.
-Start moving in both the lists, once they point to the same node, we have reached the merging node.
Please correct me if am wrong.
You (me as well) have assumed that lists merge before the cycle node. They could be merging after the cycle node.
Find the loop node, make it as the point of reference for the linked list length calculation, it would need 3 iterations totally, one to find if there's a loop in the list, 2nd to find the looping node, 3rd to find the intersection point
thanks for test case, i missed it, in such case there should be a check if the loop nodes of both the linked lists are same, else the nodes don't intersect.
The loop must be present at or after the merge point . As if not , the list end will have to point to two different nodes which isnt possible .
It isn't possible? May be a drawing will make it clear. ww w.flashpaint.com/sketchit.php?id=14261
- First find where the loop begins using 2x fast and normal pointers.
- Rayden December 14, 2011- Than find the length of each linked list considering the fact that the list ends when you encounter the loop point 2nd time it is the end.
- Than adjust the length of the long linked list so that it is the same length with the short one.
- Now start traversing both and see where they intersect.