Reputation: 1746
This question is about a particular approach on finding the intersection and NOT a general method of doing so. My approach to solving the problem at the beginning was that of kenntym's in his answer to this question. His answer is quoted below.
This takes O(M+N) time and O(1) space, where M and N are the total length of the linked lists. Maybe inefficient if the common part is very long (i.e. M,N >> m,n)
Traverse the two linked list to find M and N.
Get back to the heads, then traverse |M − N| nodes on the longer list.
Now walk in lock step and compare the nodes until you found the common ones.
I have trouble understanding the 3rd solution of 160. Intersection of Two Linked Lists on Leetcode. The approach is different but I feel it might be similar to the above solution. Could anyone show me how the two could be similar? I still can't see how one gets to the intersection from this. The solution presented there is:
Approach #3 (Two Pointers) [Accepted]
Maintain two pointers pA and pB initialized at the head of A and B, respectively. Then let them both traverse through the lists, one node at a time.
When pA reaches the end of a list, then redirect it to the head of B (yes, B, that's right.); similarly when pB reaches the end of a list, redirect it the head of A.
If at any point pA meets pB, then pA/pB is the intersection node.
To see why the above trick would work, consider the following two lists: A = {1,3,5,7,9,11} and B = {2,4,9,11}, which are intersected at node '9'. Since B.length (=4) < A.length (=6), pB would reach the end of the merged list first, because pB traverses exactly 2 nodes less than pA does. By redirecting pB to head A, and pA to head B, we now ask pB to travel exactly 2 more nodes than pA would. So in the second iteration, they are guaranteed to reach the intersection node at the same time.
If two lists have intersection, then their last nodes must be the same one. So when pA/pB reaches the end of a list, record the last element of A/B respectively. If the two last elements are not the same one, then the two lists have no intersections.
Upvotes: 1
Views: 414
Reputation: 61032
They both rely on getting the pointers such that they are the same distance from the intersection, then walking them forward simultaneously until they meet.
Your first approach explicitly calculates the number of times you have to walk the pointer on the longer list forward, while your second approach does this implicitly by making both pointers take (m+n) steps.
I like the second one a little more, because there's no point at which you're walking just one of the pointers forward, both pointers move on every iteration. The first one may be more generalizable to 3+ lists, because you would have to fully traverse each list only once.
Upvotes: 2