![]() |
VOOZH | about |
Given two singly distinct linked lists, create a new linked list that contains the intersection of elements present in both lists.
Note: The order of nodes in this list should be the same as they nodes appear in LinkedList1.
Examples:
Input: LinkedList1: 9->6->4->2->3->8 , LinkedList2: 1->2->8->6
👁 Image
Output: 6->2->8
Explanation: Nodes 6, 2 and 8 are common in both of the lists and the order will be according to LinkedList1.
Input: LinkedList1: 5->3->1->13->14 , LinkedList2: 3->13
👁 Image
Output: 3->13
Explanation: Nodes 3 and 13 are common in both of the lists and the order will be according to LinkedList1.Input:
head1: 4 -> 2 -> 4 -> 1 -> 2 -> 8
head2: 2 -> 4 -> 6 -> 2 -> 4
Output:
Intersection: 4 -> 2
Explanation: Common elements in both lists are 4 and 2. Even though they appear multiple times, each element is included only once in the intersection list.
Table of Content
Traverse the first linked list and for each element, check whether it exists in the second linked list. If yes and not already added, insert it into the result list.
Intersection: 6 2 8
Sort both linked lists and use two pointers to efficiently find common elements.
Steps
Intersection: 2 6 8
Store elements of the first list in a hash set. Then traverse the second list and check if each element exists in the set. Add to result while avoiding duplicates.
Algorithm:
tail as NULL and traverse first list Intersection: 4 2
Time Complexity: O(m+n) , where m and n are number of elements present in first and second lists respectively.
Auxiliary Space: O(m), set stores elements of one list only