Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. Order of elements in output lists doesn’t matter.
Input: List1: 10 -> 15 -> 4 -> 20 list2: 8 -> 4 -> 2 -> 10 Output: Intersection List: 4 -> 10 Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
We have already discussed Method-1 and Method-2 of this question.
In this post, its Method-3 (Using Hashing) is discussed with a Time Complexity of O(m+n) i.e. better than both methods discussed earlier.
Implementation: 1- Start traversing both the lists. a) Store the current element of both lists with its occurrence in the map. 2- For Union: Store all the elements of the map in the resultant list. 3- For Intersection: Store all the elements only with an occurrence of 2 as 2 denotes that they are present in both the lists.
Below is C++ implementation of above steps.
First list is 5 4 3 2 1 Second list is 6 5 3 1 Intersection list is 3 5 1 Union list is 3 4 6 5 2 1
We can also handle the case of duplicates by maintaining separate Hash for both the lists.
Time Complexity : O(m + n)
Auxiliary Space : O(m + n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.