Professional Documents
Culture Documents
Sol
Sol
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.
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.