Given two lists sorted in increasing order, return a new list representing their intersection. The new list should be made with its own memory – the original lists should not be changed.

For example,

Input:
 
First List: 1 —> 4 —> 7 —> 10 —> null
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> null
 
Output: 4 —> 10 —> null

Practice this problem

The strategy is to advance up both lists and build the result list as we go. When the current point in both lists is the same, add a node to the result. Otherwise, advance whichever list is smaller. By exploiting the fact that both lists are sorted, we only traverse each list once.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> NULL
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> NULL
 
After Intersection: 4 —> 10 —> NULL

Java


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> null
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> null
 
After Intersection: 4 —> 10 —> null

Python


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> None
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> None
 
After Intersection: 4 —> 10 —> None

To build up the result list, we can also use both the dummy node and local reference strategy. These solutions are implementated below:

1. Using Dummy Node

C


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> NULL
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> NULL
 
After Intersection: 4 —> 10 —> NULL

Java


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> null
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> null
 
After Intersection: 4 —> 10 —> null

Python


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> None
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> None
 
After Intersection: 4 —> 10 —> None

2. Using Local References

C


Download  Run Code

Output:

First List: 1 —> 4 —> 7 —> 10 —> NULL
Second List: 2 —> 4 —> 6 —> 8 —> 10 —> NULL
 
After Intersection: 4 —> 10 —> NULL

The time complexity of the above solution is O(m + n), where m and n are the total number of nodes in the first and second list, respectively. The auxiliary space required by the program is constant.

 
Exercise: Write recursive solution for this problem.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf