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.
C++
#include<bits/stdc++.h>usingnamespacestd;// Structure of NodestructNode{intdata;Node*next;Node(intx){data=x;next=nullptr;}};// Function to check if value exists in result listboolisPresent(Node*head,intvalue){while(head){if(head->data==value)returntrue;head=head->next;}returnfalse;}// Naive union Node*makeUnion(Node*head1,Node*head2){Node*result=nullptr;Node*tail=nullptr;while(head1){if(!isPresent(result,head1->data)){Node*newNode=newNode(head1->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head1=head1->next;}while(head2){if(!isPresent(result,head2->data)){Node*newNode=newNode(head2->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head2=head2->next;}returnresult;}// Print Linked ListvoidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" -> ";head=head->next;}cout<<endl;}// Driver Codeintmain(){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------Node*head1=newNode(9);head1->next=newNode(6);head1->next->next=newNode(4);head1->next->next->next=newNode(3);head1->next->next->next->next=newNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------Node*head2=newNode(1);head2->next=newNode(2);head2->next->next=newNode(8);head2->next->next->next=newNode(6);head2->next->next->next->next=newNode(2);Node*unionList=makeUnion(head1,head2);cout<<"Union: ";printList(unionList);return0;}
C
#include<stdio.h>#include<stdlib.h>// Structure of NodestructNode{intdata;structNode*next;};// Function to check if value exists in result listintisPresent(structNode*head,intvalue){while(head){if(head->data==value)return1;head=head->next;}return0;}// Naive union structNode*makeUnion(structNode*head1,structNode*head2){structNode*result=NULL;structNode*tail=NULL;while(head1){if(!isPresent(result,head1->data)){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=head1->data;newNode->next=NULL;if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head1=head1->next;}while(head2){if(!isPresent(result,head2->data)){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=head2->data;newNode->next=NULL;if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head2=head2->next;}returnresult;}// Print Linked ListvoidprintList(structNode*head){while(head){printf("%d",head->data);if(head->next)printf(" -> ");head=head->next;}printf("\n");}// Driver Codeintmain(){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------structNode*head1=(structNode*)malloc(sizeof(structNode));head1->data=9;head1->next=(structNode*)malloc(sizeof(structNode));head1->next->data=6;head1->next->next=(structNode*)malloc(sizeof(structNode));head1->next->next->data=4;head1->next->next->next=(structNode*)malloc(sizeof(structNode));head1->next->next->next->data=3;head1->next->next->next->next=(structNode*)malloc(sizeof(structNode));head1->next->next->next->next->data=8;// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------structNode*head2=(structNode*)malloc(sizeof(structNode));head2->data=1;head2->next=(structNode*)malloc(sizeof(structNode));head2->next->data=2;head2->next->next=(structNode*)malloc(sizeof(structNode));head2->next->next->data=8;head2->next->next->next=(structNode*)malloc(sizeof(structNode));head2->next->next->next->data=6;head2->next->next->next->next=(structNode*)malloc(sizeof(structNode));head2->next->next->next->next->data=2;structNode*unionList=makeUnion(head1,head2);printf("Union: ");printList(unionList);return0;}
Java
importjava.util.*;// Structure of NodeclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassGfG{// Function to check if value exists in result listpublicstaticbooleanisPresent(Nodehead,intvalue){while(head!=null){if(head.data==value)returntrue;head=head.next;}returnfalse;}// Naive union publicstaticNodemakeUnion(Nodehead1,Nodehead2){Noderesult=null;Nodetail=null;while(head1!=null){if(!isPresent(result,head1.data)){NodenewNode=newNode(head1.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head1=head1.next;}while(head2!=null){if(!isPresent(result,head2.data)){NodenewNode=newNode(head2.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}// Print Linked ListpublicstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}// Driver Codepublicstaticvoidmain(String[]args){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------Nodehead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------Nodehead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);NodeunionList=makeUnion(head1,head2);System.out.print("Union: ");printList(unionList);}}
Python
fromtypingimportOptional# Structure of NodeclassNode:def__init__(self,data):self.data=dataself.next=None# Function to check if value exists in result list@staticmethoddefisPresent(head:Optional['Node'],value:int)->bool:whilehead:ifhead.data==value:returnTruehead=head.nextreturnFalse# Naive union @staticmethoddefmakeUnion(head1:Optional['Node'],head2:Optional['Node'])->Optional['Node']:result=Nonetail=Nonewhilehead1:ifnotNode.isPresent(result,head1.data):newNode=Node(head1.data)ifnotresult:result=tail=newNodeelse:tail.next=newNodetail=newNodehead1=head1.nextwhilehead2:ifnotNode.isPresent(result,head2.data):newNode=Node(head2.data)ifnotresult:result=tail=newNodeelse:tail.next=newNodetail=newNodehead2=head2.nextreturnresult# Print Linked List@staticmethoddefprintList(head:Optional['Node'])->None:whilehead:print(head.data,end='')ifhead.next:print(' -> ',end='')head=head.nextprint()# Driver Codeif__name__=="__main__":# -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------head1=Node(9)head1.next=Node(6)head1.next.next=Node(4)head1.next.next.next=Node(3)head1.next.next.next.next=Node(8)# -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------head2=Node(1)head2.next=Node(2)head2.next.next=Node(8)head2.next.next.next=Node(6)head2.next.next.next.next=Node(2)unionList=Node.makeUnion(head1,head2)print("Union: ",end='')Node.printList(unionList)
C#
usingSystem;// Structure of NodepublicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}publicclassGfG{// Function to check if value exists in result listpublicstaticboolIsPresent(Nodehead,intvalue){while(head!=null){if(head.data==value)returntrue;head=head.next;}returnfalse;}// Naive union publicstaticNodeMakeUnion(Nodehead1,Nodehead2){Noderesult=null;Nodetail=null;while(head1!=null){if(!IsPresent(result,head1.data)){NodenewNode=newNode(head1.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head1=head1.next;}while(head2!=null){if(!IsPresent(result,head2.data)){NodenewNode=newNode(head2.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}// Print Linked ListpublicstaticvoidPrintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}// Driver CodepublicstaticvoidMain(string[]args){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------Nodehead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------Nodehead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);NodeunionList=MakeUnion(head1,head2);Console.Write("Union: ");PrintList(unionList);}}
JavaScript
/* Structure of Node */functionNode(data){this.data=data;this.next=null;}/* Function to check if value exists in result list */functionisPresent(head,value){while(head){if(head.data===value)returntrue;head=head.next;}returnfalse;}/* Naive union */functionmakeUnion(head1,head2){letresult=null;lettail=null;while(head1){if(!isPresent(result,head1.data)){constnewNode=newNode(head1.data);if(!result)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head1=head1.next;}while(head2){if(!isPresent(result,head2.data)){constnewNode=newNode(head2.data);if(!result)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}/* Print Linked List */functionprintList(head){letcurrent=head;letresult='';while(current){result+=current.data;if(current.next)result+=' -> ';current=current.next;}console.log(result);}/* Driver Code */(functionmain(){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------lethead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------lethead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);constunionList=makeUnion(head1,head2);console.log('Union:');printList(unionList);})();
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.
C++
#include<iostream>#include<unordered_set>usingnamespacestd;// Node definitionclassNode{public:intdata;Node*next;Node(intx){data=x;next=NULL;}};// Union using hashing Node*makeUnion(Node*head1,Node*head2){unordered_set<int>seen;Node*result=NULL;Node*tail=NULL;// Process first listwhile(head1){if(seen.find(head1->data)==seen.end()){seen.insert(head1->data);Node*newNode=newNode(head1->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head1=head1->next;}// Process second listwhile(head2){if(seen.find(head2->data)==seen.end()){seen.insert(head2->data);Node*newNode=newNode(head2->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head2=head2->next;}returnresult;}// Print functionvoidprintList(Node*head){while(head){cout<<head->data;if(head->next)cout<<" -> ";head=head->next;}cout<<endl;}// Driver Codeintmain(){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------Node*head1=newNode(9);head1->next=newNode(6);head1->next->next=newNode(4);head1->next->next->next=newNode(3);head1->next->next->next->next=newNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------Node*head2=newNode(1);head2->next=newNode(2);head2->next->next=newNode(8);head2->next->next->next=newNode(6);head2->next->next->next->next=newNode(2);Node*unionList=makeUnion(head1,head2);cout<<"Union: ";printList(unionList);return0;}
C
#include<stdio.h>#include<stdlib.h>#include<stdbool.h>// Node definitiontypedefstructNode{intdata;structNode*next;}Node;// Function to create a new NodeNode*createNode(intx){Node*newNode=(Node*)malloc(sizeof(Node));newNode->data=x;newNode->next=NULL;returnnewNode;}// Union using hashing Node*makeUnion(Node*head1,Node*head2){boolseen[100]={false};Node*result=NULL;Node*tail=NULL;// Process first listwhile(head1){if(!seen[head1->data]){seen[head1->data]=true;Node*newNode=createNode(head1->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head1=head1->next;}// Process second listwhile(head2){if(!seen[head2->data]){seen[head2->data]=true;Node*newNode=createNode(head2->data);if(!result)result=tail=newNode;else{tail->next=newNode;tail=newNode;}}head2=head2->next;}returnresult;}// Print functionvoidprintList(Node*head){while(head){printf("%d",head->data);if(head->next)printf(" -> ");head=head->next;}printf("\n");}// Driver Codeintmain(){// -------- List 1: 9 -> 6 -> 4 -> 3 -> 8 --------structNode*head1=createNode(9);head1->next=createNode(6);head1->next->next=createNode(4);head1->next->next->next=createNode(3);head1->next->next->next->next=createNode(8);// -------- List 2: 1 -> 2 -> 8 -> 6 -> 2 --------structNode*head2=createNode(1);head2->next=createNode(2);head2->next->next=createNode(8);head2->next->next->next=createNode(6);head2->next->next->next->next=createNode(2);structNode*unionList=makeUnion(head1,head2);printf("Union: ");printList(unionList);return0;}
Java
importjava.util.HashSet;// Node definitionclassNode{intdata;Nodenext;Node(intx){data=x;next=null;}}publicclassMain{// Union using hashing staticNodemakeUnion(Nodehead1,Nodehead2){HashSet<Integer>seen=newHashSet<>();Noderesult=null;Nodetail=null;// Process first listwhile(head1!=null){if(!seen.contains(head1.data)){seen.add(head1.data);NodenewNode=newNode(head1.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head1=head1.next;}// Process second listwhile(head2!=null){if(!seen.contains(head2.data)){seen.add(head2.data);NodenewNode=newNode(head2.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}// Print functionstaticvoidprintList(Nodehead){while(head!=null){System.out.print(head.data);if(head.next!=null)System.out.print(" -> ");head=head.next;}System.out.println();}// Driver Codepublicstaticvoidmain(String[]args){Nodehead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);Nodehead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);NodeunionList=makeUnion(head1,head2);System.out.print("Union: ");printList(unionList);}}
Python
# Node definitionclassNode:def__init__(self,x):self.data=xself.next=None# Union using hashing defmakeUnion(head1,head2):seen=set()result=Nonetail=None# Process first listwhilehead1:ifhead1.datanotinseen:seen.add(head1.data)newNode=Node(head1.data)ifnotresult:result=tail=newNodeelse:tail.next=newNodetail=newNodehead1=head1.next# Process second listwhilehead2:ifhead2.datanotinseen:seen.add(head2.data)newNode=Node(head2.data)ifnotresult:result=tail=newNodeelse:tail.next=newNodetail=newNodehead2=head2.nextreturnresult# Print functiondefprintList(head):whilehead:print(head.data,end="")ifhead.next:print(" -> ",end="")head=head.nextprint()# Driver Codehead1=Node(9)head1.next=Node(6)head1.next.next=Node(4)head1.next.next.next=Node(3)head1.next.next.next.next=Node(8)head2=Node(1)head2.next=Node(2)head2.next.next=Node(8)head2.next.next.next=Node(6)head2.next.next.next.next=Node(2)unionList=makeUnion(head1,head2)print("Union:",end=" ")printList(unionList)
C#
usingSystem;usingSystem.Collections.Generic;publicclassProgram{// Node definitionpublicclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}// Union using hashing publicstaticNodeMakeUnion(Nodehead1,Nodehead2){HashSet<int>seen=newHashSet<int>();Noderesult=null;Nodetail=null;while(head1!=null){if(!seen.Contains(head1.data)){seen.Add(head1.data);NodenewNode=newNode(head1.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head1=head1.next;}while(head2!=null){if(!seen.Contains(head2.data)){seen.Add(head2.data);NodenewNode=newNode(head2.data);if(result==null)result=tail=newNode;else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}// Print functionpublicstaticvoidPrintList(Nodehead){while(head!=null){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}// Driver CodepublicstaticvoidMain(string[]args){Nodehead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);Nodehead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);NodeunionList=MakeUnion(head1,head2);Console.Write("Union: ");PrintList(unionList);}}
JavaScript
// Node definitionclassNode{constructor(x){this.data=x;this.next=null;}}// Union using hashingfunctionmakeUnion(head1,head2){letseen=newSet();letresult=null;lettail=null;// Process first listwhile(head1){if(!seen.has(head1.data)){seen.add(head1.data);letnewNode=newNode(head1.data);if(!result){result=tail=newNode;}else{tail.next=newNode;tail=newNode;}}head1=head1.next;}// Process second listwhile(head2){if(!seen.has(head2.data)){seen.add(head2.data);letnewNode=newNode(head2.data);if(!result){result=tail=newNode;}else{tail.next=newNode;tail=newNode;}}head2=head2.next;}returnresult;}// Print functionfunctionprintList(head){while(head){process.stdout.write(head.data.toString());if(head.next){process.stdout.write(" -> ");}head=head.next;}console.log();}// Driver Code// Driver Code// -------- List 1 --------lethead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);// -------- List 2 --------lethead2=newNode(1);head2.next=newNode(2);head2.next.next=newNode(8);head2.next.next.next=newNode(6);head2.next.next.next.next=newNode(2);letunionList=makeUnion(head1,head2);process.stdout.write("Union: ");printList(unionList);