Find Intersection Of Two Singly Linked Lists
Given two singly linked lists, find their intersection if any.
The intersection is the node where the two lists merge, the first node that belongs to both lists, node 2 in the following illustration:
Input: Pointers to nodes 1 (first list) and 5 (second list):
The lists intersect in node 4.
Input Parameters: Function has two arguments: L1 and L2, the pointers to heads of the singly linked lists.
Output: Function must return an integer, the value from the intersection node or -1 if no intersection exists.
Let us first try to solve a simpler problem. What if the two linked lists are of the same length? We could start comparing from the first node of both lists. If the two nodes are the same (same address) then it is the intersection node else we advance both pointers to their next nodes and again compare and so on. If we reach the end of both lists, it means they do not intersect.
Now suppose one list is longer than the other by X nodes. It is easy to see that the intersection cannot be found among the first X nodes of the longer list. X is easy to calculate by measuring the length of each list. Then we can reduce the problem to the simpler one by skipping the first X nodes in the longer list. Using this approach we would walk through the lists two times total: once for measuring their lengths and once again for comparing the nodes.
O(N) where N is the length of the longer list (or lengths of the two lists combined).
Auxiliary Space Used:
O(N) where N is the size of input.