This question may be old, but I couldn’t think of an answer.
Say, there are two lists of different lengths, merging at a point; how do we know where the merging point is?
Conditions:
- We don’t know the length
- We should parse each list only once.

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If
the following algorithm would be the solution.
First, the numbers. Assume the first list is of length
a+cand the second one is of lengthb+c, wherecis the length of their common “tail” (after the mergepoint). Let’s denote them as follows:Since we don’t know the length, we will calculate
xandywithout additional iterations; you’ll see how.Then, we iterate each list and reverse them while iterating! If both iterators reach the merge point at the same time, then we find it out by mere comparing. Otherwise, one pointer will reach the merge point before the other one.
After that, when the other iterator reaches the merge point, it won’t proceed to the common tail. Instead will go back to the former beginning of the list that had reached merge-point before! So, before it reaches the end of the changed list (i.e. the former beginning of the other list), he will make
a+b+1iterations total. Let’s call itz+1.The pointer that reached the merge-point first, will keep iterating, until reaches the end of the list. The number of iterations it made should be calculated and is equal to
x.Then, this pointer iterates back and reverses the lists again. But now it won’t go back to the beginning of the list it originally started from! Instead, it will go to the beginning of the other list! The number of iterations it made should be calculated and equal to
y.So we know the following numbers:
From which we determine that
Which solves the problem.