Given two singly linked lists, create a new linked list that contains the union of elements present in both lists.
Each element should appear only once in the resulting list (no duplicates allowed).
The order of elements in the resulting list should be, all distinct nodes of the first list then remaining distinct nodes (nodes that are not in first) of the second list
[Naive Approach] Using Two Nested Loops - O(n * m) Time and O(n + m) Space
The idea is to build the union list by traversing both linked lists and adding elements only if they are not already present in the result. To check duplicates, we traverse the result list every time before inserting a new node.
Algorithm:
Initialize an empty result linked list. Traverse the first list:
For each node, check if it already exists in the result.
If not present, insert it at the end of the result.
Traverse the second list:
Again, check for each node if it exists in the result.
If not, insert it.
Return the final result list.
Output
Union: 9 -> 6 -> 4 -> 3 -> 8 -> 1 -> 2
[Expected Approach] Using Hashing – O(n + m) Time and O(n + m) Space
The idea is to Use a hash set to keep track of unique elements. Traverse the first linked list and add unseen elements to both the set and result list. Then traverse the second list and insert only those elements that are not already present, ensuring no duplicates.
Algorithm:
Initialize a hash set and result list pointers.
Traverse first list and insert unique elements into set and result list.
Traverse second list and check each element in the set. Add only unseen elements to the result list, skip duplicates.