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] Two Nested Loops - O(n * m) Time and O(n + m) Space
The idea is to traverse both linked lists and add each element to the result list only if it is not already present. Process the first list before the second to preserve the order of first occurrences.
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;}intmain(){// 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");}intmain(){// 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
// 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();}publicstaticvoidmain(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
# Structure of NodeclassNode:def__init__(self,data):self.data=dataself.next=None# Function to check if value exists in result listdefisPresent(head,value):whilehead:ifhead.data==value:returnTruehead=head.nextreturnFalse# Naive uniondefmakeUnion(head1,head2):result=Nonetail=Nonewhilehead1:ifnotisPresent(result,head1.data):newNode=Node(head1.data)ifresultisNone:result=tail=newNodeelse:tail.next=newNodetail=newNodehead1=head1.nextwhilehead2:ifnotisPresent(result,head2.data):newNode=Node(head2.data)ifresultisNone:result=tail=newNodeelse:tail.next=newNodetail=newNodehead2=head2.nextreturnresult# Print Linked ListdefprintList(head):whilehead:print(head.data,end="")ifhead.next:print(" -> ",end="")head=head.nextprint()if__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=makeUnion(head1,head2)print("Union: ",end="")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();}publicstaticvoidMain(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 NodeclassNode{constructor(x){this.data=x;this.next=null;}}// Function to check if value exists in result listfunctionisPresent(head,value){while(head){if(head.data===value)returntrue;head=head.next;}returnfalse;}// Naive unionfunctionmakeUnion(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 ListfunctionprintList(head){constparts=[];while(head){parts.push(head.data);head=head.next;}console.log(parts.join(" -> "));}// Driver code//List 1: 9 -> 6 -> 4 -> 3 -> 8 consthead1=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 consthead2=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);process.stdout.write("Union: ");printList(unionList);
Output
Union: 9 -> 6 -> 4 -> 3 -> 8 -> 1 -> 2
[Expected Approach] Hashing - O(n + m) Time and O(n + m) Space
The idea is to use a set to keep track of elements that have already been added to the result list.
Create an empty result linked list and a set.
Traverse the first linked list. For each element, check whether it is present in the set.
If it is not present, add it to the set and append it to the result list.
Traverse the second linked list and perform the same check.
Append an element only if it is not already present in the set.
Return the result list.
By processing the first list before the second, the approach preserves the order of first occurrences and ensures that every element appears only once in the union.
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 -> 8Node*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();}publicstaticvoidmain(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 hashingdefmakeUnion(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()if__name__=="__main__":# List 1: 9 -> 6 -> 4 -> 3 -> 8head1=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 -> 2head2=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;// Node definitionclassNode{publicintdata;publicNodenext;publicNode(intx){data=x;next=null;}}classGFG{// Union using hashingstaticNodemakeUnion(Nodehead1,Nodehead2){HashSet<int>seen=newHashSet<int>();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){Console.Write(head.data);if(head.next!=null)Console.Write(" -> ");head=head.next;}Console.WriteLine();}staticvoidMain(){// 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
// 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 Codelethead1=newNode(9);head1.next=newNode(6);head1.next.next=newNode(4);head1.next.next.next=newNode(3);head1.next.next.next.next=newNode(8);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);