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 lsit2: 8 -> 4 -> 2 -> 10 Output: Intersection List: 4 -> 10 Union List: 2 -> 8 -> 20 -> 4 -> 15 -> 10
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.
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 of this method is O(m Log m + n Log n).
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 email@example.com. 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.
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Union and Intersection of two Linked Lists
- Union and Intersection of two linked lists | Set-3 (Hashing)
- Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
- Merge Sort for Linked Lists
- Difference of two Linked Lists using Merge sort
- Intersection of two Sorted Linked Lists
- Write a function to get the intersection point of two Linked Lists | Set 2
- Write a function to get the intersection point of two Linked Lists
- Find intersection point of two Linked Lists without finding the length
- Merge K sorted linked lists | Set 1
- Merge two sorted linked lists
- Merge k sorted linked lists | Set 2 (Using Min Heap)
- In-place Merge two linked lists without changing links of first list
- Merge two sorted linked lists such that merged list is in reverse order
Improved By : nidhi_biet