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.
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.
- 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
- Write a function to get the intersection point of two Linked Lists | Set 2
- 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)
- Merge two unsorted linked lists to get a sorted list
- 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
- Merge Sort for Doubly Linked List
- Iterative Merge Sort for Linked List
- Union and Intersection of two sorted arrays
- Sorted merge of two sorted doubly circular linked lists
Improved By : nidhi_biet