You are on page 1of 2

Solution-3 explanation:

Step 1. Find the length of lists A and B.


Step 2. Calculate the length difference. Let assume the absolute difference of
length is t.
Step 3. Move the pointer of longer list by t steps.
Step 4. Traverse both the list and find the first intersection node.

Solution-4 explanation:

Note: If there is no intersection and length of both lists are same then both
pointers will points to NULL simulatenauoly in the first traversal.
If there is no intersection and length of both lists are not same then both
pointers will points to NULL simulatenauoly in the second traversal.

Let assume the length of List A is a + c and length of List B is b + c (c is the


length of the intersected part).
Length of A + Length of B == Length of A + Length of B == a + c + b + c.
Let make ptr1 and ptr2 as start pointers of list A and list B respectively.
The idea is to traverse both pointers by same distance (a + b + c).
First traverse both the pointers until they reach to the end of their respective
lists and then to offset the length difference between the two lists we switch
both the pointers i.e. we are pointing ptr1 to head B after a + c iterations and
ptr2 to head A after b + c iterations.
In second traversal, we need to traverse ptr1 by b steps and ptr2 by a steps.
Ater a + b + c iterations, both pointers will meet to the first intersection node.

Step 1: Start the pointer at head A and head B.

In this solution we are implicitly calculating the length difference.

The pointer for the smaller list will traverse back to the beginning of the larger
list and then
offset the distance between the two lists before the pointer for the larger list
traverses the larger list completely.
Consequently, both the pointers will now need to traverse the length of equal to
that of the smaller list. This is why it works.

Brilliant solution!
Idea is to make both pointers same length :
If the two linked lists have no intersection at all, then the meeting pointer in
second iteration must be the tail node of both lists, which is null."

# the idea is if you switch head, the possible difference between length would be
countered.
# On the second traversal, they either hit or miss.
# if they meet, pa or pb would be the node we are looking for,
# if they didn't meet, they will hit the end at the same iteration, pa == pb ==
None, return either one of them is the same,None

It only takes two traversals, After they switch head, the path pa and pb pointers
have been are n+m+c and m+n+c which are the same.

you need to know the difference of length between the two lists so that you can
start traversing both of them from the same length away from the intersection
point.
When you reach the end of the shorter list from that point on you are implicitly
computing the difference between the lists.

You might also like