views:

500

answers:

3

Suppose there are two singly linked lists both of which intersect at some point and become a single linked list.

The head or start pointers of both the lists are known, but the intersecting node is not known. Also, the number of nodes in each of the list before they intersect are unknown and both list may have it different i.e. List1 may have n nodes before it reaches intersection point and List2 might have m nodes before it reaches intersection point where m and n may be

  • m = n,
  • m < n or
  • m > n

One known or easy solution is to compare every node pointer in the first list with every other node pointer in the second list by which the matching node pointers will lead us to the intersecting node. But, the time complexity in this case will O(n2) which will be high.

What is the most efficient way of finding the intersecting node?

+9  A: 
KennyTM
I like this! +1.
j_random_hacker
Accepting this answer as this doesn't need modification of the list and also does not eat extra space. But, I am still wondering if there aren't any better solutions than this. Anyways, Thanks a lot for your reply and others also.
Jay
+3  A: 

If possible, you could add a 'color' field or similar to the nodes. Iterate over one of the lists, coloring the nodes as you go. Then iterate over the second list. As soon as you reach a node that is already colored, you have found the intersection.

calmh
+1  A: 

Dump the contents of both lists into one hash table. first collision is your intersection.

ddyer
If there is 2 linkedlist like 1-2-3-4-3-5 and 9-8-3-5. And the 2nd linkedlist intersect the 1st one in 2nd 3rd. But if we use some hash table then it will clash at first position of 3.
Pritam Karmakar
one linked list can't contain 3 twice unless it's already twistedinto a "6" instead of a linerar list.
ddyer