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 Explanation: In this two lists 4 and 10 nodes are common. The union lists contains all the nodes of both the lists. Input: List1: 1 -> 2 -> 3 -> 4 List2: 3 -> 4 -> 8 -> 10 Output: Intersection List: 3 -> 4 Union List: 1 -> 2 -> 3 -> 4 -> 8 -> 10 Explanation: In this two lists 4 and 3 nodes are common. The union lists contains all the nodes of both the lists.
Implementation: Following are the steps to be followed to get union and intersection lists. 1) Sort both Linked Lists using merge sort. This step takes O(mLogm) time. 2) Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time.
- Sort both Linked Lists using merge sort.
- Linearly scan both sorted lists to get the union and intersection.
- Perform merge like operation on both linked lists, Keep to a pointer which points initially to the first node of both lists.
- Compare both the nodes until and unless both the pointers are not null.
- if equal add it to the intersection list and union list and move to next node of both the pointers
- if not equal then insert the smaller pointer value into union list and move to the next node
- If one of the pointers is null then traverse the other list and all its nodes to union list.
Just like Method 1, this method also assumes that there are distinct elements in the lists.
First list is 4 10 11 15 20 Second list is 2 4 8 10 Intersection list is 10 4 Union list is 20 15 11 10 8 4 2
- Time complexity: O(m Log m + n Log n).
Time required to sort the lists are n log n and m log m and to find union and intersection linear time is required.
- Auxiliary Space: O(m+n).
If the output is stored then O(m+n) space is required.
In the next post, Method-3 will be discussed i.e. using hashing.
This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.