Wednesday, October 27, 2010

I decided to post a interview question everyday

Amazon Interview Question:

Find the point where two Linkedlists merge?


To find whether two linkedlist merge is not hard, we can just traverse each list and see if the rear is the same thing. However, this question wants to know the point where two linkedlist merge.

My first thought is to reverse the linkedlist. Then, we can easily compare and see if the linkedlist can merge by comparison. However, the interviewer didn't want to modify the data. In this way, he gave me a hint about how to know if two people are running at the same speed, but starts at different starting points. How do you know the conjunction they meet each other?


Then here comes the solution: get the length of each linkedlist and then start the longer list first with the differences of the length. Then compare them just like what we did after reverse the linkedlist.


Here is the code in Java

public int mergePoint(Node root1, Node root2){
int length1 = 0;
int lenght2 = 0;


while(root1!=null) {
length1++;
pre1 = root1;
root1 = root1.next;
}
while(root2!=null) {
length2++;
pre2 = root2;
root2 = root2.next;
}

if(pre1 != pre2) return -1;

if(length1 > length2)
......

}

No comments:

Post a Comment