Find common elements in three linked lists
Last Updated :
09 Jan, 2023
Given three linked lists, find all common elements among the three linked lists.
Examples:
Input :
10 15 20 25 12
10 12 13 15
10 12 15 24 25 26
Output : 10 12 15
Input :
1 2 3 4 5
1 2 3 4 6 9 8
1 2 4 5 10
Output : 1 2 4
Method 1 : (Simple)
Use three-pointers to iterate the given three linked lists and if any element common print that element.
Time complexity of the above solution will be O(N*N*N)
Method 2 : (Use Merge Sort)
In this method, we first sort the three lists and then we traverse the sorted lists to get the intersection.
Following are the steps to be followed to get intersection of three lists:
- Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
- Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
- Sort the third Linked List using merge sort. This step takes O(pLogp) time. Refer this post for details of this step.
- Linearly scan three sorted lists to get the intersection. This step takes O(m + n + p) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.
Time complexity of this method is O(mLogm + nLogn + plogp) which is better than method 1’s time complexity.
Method 3 : (Hashing)
Following are the steps to be followed to get intersection of three lists using hashing:
- Create an empty hash table. Iterate through the first linked list and mark all the element frequency as 1 in the hash table. This step takes O(m) time.
- Iterate through the second linked list and if current element frequency is 1 in hash table mark it as 2. This step takes O(n) time.
- Iterate the third linked list and if the current element frequency is 2 in hash table mark it as 3. This step takes O(p) time.
- Now iterate first linked list again to check the frequency of elements. if an element with frequency three exist in hash table, it will be present in the intersection of three linked lists. This step takes O(m) time.
Time complexity of this method is O(m + n + p) which is better than time complexity of method 1 and 2.
Below is the implementation of the above idea.
C++
// C++ program to find common element
// in three unsorted linked list
#include <bits/stdc++.h>
#define max 1000000
using namespace std;
/* Link list node */
struct Node {
int data;
struct Node* next;
};
/* A utility function to insert a node at the
beginning of a linked list */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node *)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
/* print the common element in between
given three linked list*/
void Common(struct Node* head1,
struct Node* head2, struct Node* head3)
{
// Creating empty hash table;
unordered_map<int, int> hash;
struct Node* p = head1;
while (p != NULL) {
// set frequency by 1
hash[p->data] = 1;
p = p->next;
}
struct Node* q = head2;
while (q != NULL) {
// if the element is already exist in the
// linked list set its frequency 2
if (hash.find(q->data) != hash.end())
hash[q->data] = 2;
q = q->next;
}
struct Node* r = head3;
while (r != NULL) {
if (hash.find(r->data) != hash.end() &&
hash[r->data] == 2)
// if the element frequency is 2 it means
// its present in both the first and second
// linked list set its frequency 3
hash[r->data] = 3;
r = r->next;
}
for (auto x : hash) {
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (x.second == 3)
cout << x.first << " ";
}
}
// Driver code
int main()
{
// first list
struct Node* head1 = NULL;
push(&head1, 20);
push(&head1, 5);
push(&head1, 15);
push(&head1, 10);
// second list
struct Node* head2 = NULL;
push(&head2, 10);
push(&head2, 20);
push(&head2, 15);
push(&head2, 8);
// third list
struct Node* head3 = NULL;
push(&head3, 10);
push(&head3, 2);
push(&head3, 15);
push(&head3, 20);
Common(head1, head2, head3);
return 0;
}
Java
// Java program to find common element
// in three unsorted linked list
import java.util.*;
class GFG
{
static int max = 1000000;
/* Link list node */
static class Node
{
int data;
Node next;
};
/* A utility function to insert a node
at the beginning of a linked list */
static Node push(Node head_ref,
int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
/* print the common element in between
given three linked list*/
static void Common(Node head1,
Node head2,
Node head3)
{
// Creating empty hash table;
HashMap<Integer,
Integer> hash = new HashMap<Integer,
Integer>();
Node p = head1;
while (p != null)
{
// set frequency by 1
hash. put(p.data, 1);
p = p.next;
}
Node q = head2;
while (q != null)
{
// if the element is already exist in the
// linked list set its frequency 2
if (hash.containsKey(q.data))
hash. put(q.data, 2);
q = q.next;
}
Node r = head3;
while (r != null)
{
if (hash.containsKey(r.data)&&
hash.get(r.data) == 2)
// if the element frequency is 2 it means
// its present in both the first and second
// linked list set its frequency 3
hash. put(r.data, 3);
r = r.next;
}
for (Map.Entry<Integer,
Integer> x : hash.entrySet())
{
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (x.getValue() == 3)
System.out.println(x.getKey() + " ");
}
}
// Driver code
public static void main(String[] args)
{
// first list
Node head1 = null;
head1 = push(head1, 20);
head1 = push(head1, 5);
head1 = push(head1, 15);
head1 = push(head1, 10);
// second list
Node head2 = null;
head2 = push(head2, 10);
head2 = push(head2, 20);
head2 = push(head2, 15);
head2 = push(head2, 8);
// third list
Node head3 = null;
head3 = push(head3, 10);
head3 = push(head3, 2);
head3 = push(head3, 15);
head3 = push(head3, 20);
Common(head1, head2, head3);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to find common element
# in three unsorted linked list
max = 1000000
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# A utility function to insert a node at the
# beginning of a linked list
def push( head_ref, new_data):
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Print the common element in between
# given three linked list
def Common(head1, head2, head3):
# Creating empty hash table;
hash = dict()
p = head1
while (p != None):
# Set frequency by 1
hash[p.data] = 1
p = p.next
q = head2
while (q != None):
# If the element is already exist in the
# linked list set its frequency 2
if (q.data in hash):
hash[q.data] = 2
q = q.next
r = head3
while (r != None):
if (r.data in hash) and hash[r.data] == 2:
# If the element frequency is 2 it means
# its present in both the first and second
# linked list set its frequency 3
hash[r.data] = 3
r = r.next
for x in hash.keys():
# If current frequency is 3 its means
# element is common in all the given
# linked list
if (hash[x] == 3):
print(x, end = ' ')
# Driver code
if __name__=='__main__':
# First list
head1 = None
head1 = push(head1, 20)
head1 = push(head1, 5)
head1 = push(head1, 15)
head1 = push(head1, 10)
# Second list
head2 = None
head2 = push(head2, 10)
head2 = push(head2, 20)
head2 = push(head2, 15)
head2 = push(head2, 8)
# Third list
head3 = None
head3 = push(head3, 10)
head3 = push(head3, 2)
head3 = push(head3, 15)
head3 = push(head3, 20)
Common(head1, head2, head3)
# This code is contributed by rutvik_56
C#
// C# program to find common element
// in three unsorted linked list
using System;
using System.Collections.Generic;
class GFG
{
static int max = 1000000;
/* Link list node */
public class Node
{
public int data;
public Node next;
};
/* A utility function to insert a node
at the beginning of a linked list */
static Node push(Node head_ref,
int new_data)
{
Node new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
/* print the common element in between
given three linked list*/
static void Common(Node head1,
Node head2,
Node head3)
{
// Creating empty hash table;
Dictionary<int,
int> hash = new Dictionary<int,
int>();
Node p = head1;
while (p != null)
{
// set frequency by 1
hash.Add(p.data, 1);
p = p.next;
}
Node q = head2;
while (q != null)
{
// if the element is already exist in the
// linked list set its frequency 2
if (hash.ContainsKey(q.data))
hash[q.data] = 2;
q = q.next;
}
Node r = head3;
while (r != null)
{
if (hash.ContainsKey(r.data)&&
hash[r.data] == 2)
// if the element frequency is 2 it means
// its present in both the first and
// second linked list set its frequency 3
hash[r.data] = 3;
r = r.next;
}
foreach(KeyValuePair<int, int> x in hash)
{
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (x.Value == 3)
Console.Write(x.Key + " ");
}
}
// Driver code
public static void Main(String[] args)
{
// first list
Node head1 = null;
head1 = push(head1, 20);
head1 = push(head1, 5);
head1 = push(head1, 15);
head1 = push(head1, 10);
// second list
Node head2 = null;
head2 = push(head2, 10);
head2 = push(head2, 20);
head2 = push(head2, 15);
head2 = push(head2, 8);
// third list
Node head3 = null;
head3 = push(head3, 10);
head3 = push(head3, 2);
head3 = push(head3, 15);
head3 = push(head3, 20);
Common(head1, head2, head3);
}
}
// This code is contributed by Princi Singh
JavaScript
<script>
// JavaScript program to find common element
// in three unsorted linked list
var max = 1000000;
/* Link list node */
class Node
{
constructor()
{
this.data = 0;
this.next = null;
}
};
/* A utility function to insert a node
at the beginning of a linked list */
function push(head_ref, new_data)
{
var new_node = new Node();
new_node.data = new_data;
new_node.next = head_ref;
head_ref = new_node;
return head_ref;
}
/* print the common element in between
given three linked list*/
function Common(head1, head2, head3)
{
// Creating empty hash table;
var hash = new Map();
var p = head1;
while (p != null)
{
// set frequency by 1
hash.set(p.data, 1);
p = p.next;
}
var q = head2;
while (q != null)
{
// if the element is already exist in the
// linked list set its frequency 2
if (hash.has(q.data))
hash.set(q.data, 2);
q = q.next;
}
var r = head3;
while (r != null)
{
if (hash.has(r.data)&&
hash.get(r.data) == 2)
// if the element frequency is 2 it means
// its present in both the first and
// second linked list set its frequency 3
hash.set(r.data, 3);
r = r.next;
}
hash.forEach((value, key) => {
// if current frequency is 3 its means
// element is common in all the given
// linked list
if (value == 3)
document.write(key + " ");
});
}
// Driver code
// first list
var head1 = null;
head1 = push(head1, 20);
head1 = push(head1, 5);
head1 = push(head1, 15);
head1 = push(head1, 10);
// second list
var head2 = null;
head2 = push(head2, 10);
head2 = push(head2, 20);
head2 = push(head2, 15);
head2 = push(head2, 8);
// third list
var head3 = null;
head3 = push(head3, 10);
head3 = push(head3, 2);
head3 = push(head3, 15);
head3 = push(head3, 20);
Common(head1, head2, head3);
</script>
Time Complexity : O(m + n + p)
Auxiliary Space : O(m + n + p)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem