Find common elements in three sorted arrays
Last Updated :
20 Mar, 2025
Given three sorted arrays in non-decreasing order, print all common elements in non-decreasing order across these arrays. If there are no such elements return an empty array. In this case, the output will be -1.
Note: In case of duplicate common elements, print only once.
Examples:
Input: arr1[] = [1, 5, 10, 20, 30], arr2[] = [5, 13, 15, 20], arr3[] = [5, 20]
Output: 5 20
Explanation: 5 and 20 are common in all the arrays.
Input: arr1[] = [2, 5, 10, 30], arr2[] = [5, 20, 34], arr3[] = [5, 13, 19]
Output: 5
Explanation: 5 is common in all the arrays.
[Naive Approach] Using Tree Map (Or Self Balancing BST) - O((n1 + n2 + n3)*log n1) Time and O(n1) Space
The basic idea is to use Tree Map for storing the common elements in three sorted arrays. This can be implemented by:
- Iterate over the first array and for each element mark its value = 1 in a self balancing BST.
- Now, iterate over the second array and for each element in the second array, mark value = 2 of only those elements which already had the value = 1 in the map. This will ensure that all the common elements among the first two arrays have value = 2 in hash table.
- Finally, iterate over the third array and for each element in the third array, mark value = 3 of only those elements which already had value = 2 in the Tree Map (or Self Balancing BST)
Important Points
- If sorted order is not required, then we can use Hashing instead of Self Balancing BST to do the work in linear time.
- In languages like Python, C# and JavaScript, there is not built in implementation of Self Balancing BST, so we use a Dictionary or Hash Table and finally do sorting.
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> commonElements(vector<int> &arr1, vector<int> &arr2, vector<int> &arr3)
{
// hash table to mark the common elements
map<int, int> mp;
// Mark all the elements in the first Array with value=1
for (int ele : arr1)
{
mp[ele] = 1;
}
// Mark all the elements which are common in first and
// second Array with value = 2
for (int ele : arr2)
{
if (mp.find(ele) != mp.end() && mp[ele] == 1)
mp[ele] = 2;
}
// Mark all the elements which are common in first,
// second and third Array with value = 3
for (int ele : arr3)
{
if (mp.find(ele) != mp.end() && mp[ele] == 2)
mp[ele] = 3;
}
// Store all the common elements
vector<int> commonElements;
for (auto ele : mp)
{
if (ele.second == 3)
commonElements.push_back(ele.first);
}
// Return the common elements which are common in all
// the three sorted Arrays
return commonElements;
}
int main()
{
// Sample Input
vector<int> arr1 = {1, 5, 10, 20, 30};
vector<int> arr2 = {5, 13, 15, 20};
vector<int> arr3 = {5, 20};
vector<int> common = commonElements(arr1, arr2, arr3);
if (common.size() == 0)
cout << -1;
for (int i = 0; i < common.size(); i++)
{
cout << common[i] << " ";
}
return 0;
}
Java
import java.util.*;
public class GfG {
// Function to find common elements in three arrays
public static ArrayList<Integer>
commonElements(ArrayList<Integer> arr1,
ArrayList<Integer> arr2,
ArrayList<Integer> arr3)
{
// TreeMap to mark the common elements
TreeMap<Integer, Integer> map = new TreeMap<>();
// Mark all the elements in the first array with
// value=1
for (int ele : arr1) {
map.put(ele, 1);
}
// Mark all the elements which are common in first
// and second array with value = 2
for (int ele : arr2) {
if (map.containsKey(ele) && map.get(ele) == 1)
map.put(ele, 2);
}
// Mark all the elements which are common in first,
// second, and third array with value = 3
for (int ele : arr3) {
if (map.containsKey(ele) && map.get(ele) == 2)
map.put(ele, 3);
}
// Store all the common elements
ArrayList<Integer> commonElements
= new ArrayList<>();
for (int ele : map.keySet()) {
if (map.get(ele) == 3)
commonElements.add(ele);
}
// Return the common elements which are common in
// all the three arrays
return commonElements;
}
public static void main(String[] args)
{
// Sample Input
ArrayList<Integer> arr1
= new ArrayList<>(List.of(1, 5, 10, 20, 30));
ArrayList<Integer> arr2
= new ArrayList<>(List.of(5, 13, 15, 20));
ArrayList<Integer> arr3
= new ArrayList<>(List.of(5, 20));
// Function call and storing result
ArrayList<Integer> common
= commonElements(arr1, arr2, arr3);
if (common.size() == 0)
System.out.print(-1);
for (int i = 0; i < common.size(); i++)
System.out.print(common.get(i) + " ");
}
}
Python
def commonElements(arr1, arr2, arr3):
# Hashing using dictionaries
count = {}
# Count occurrences in arr1
for ele in arr1:
count[ele] = 1
# Increment counts for elements in arr2
for ele in arr2:
if count.get(ele) == 1:
count[ele] = 2
# Increment counts for elements in arr3
for ele in arr3:
if count.get(ele) == 2:
count[ele] = 3
# Extract common elements in sorted order
return sorted([ele for ele in count if count[ele] == 3])
# Sample Input
arr1 = [1, 5, 10, 20, 30]
arr2 = [5, 13, 15, 20]
arr3 = [5, 20]
# Function call
common = commonElements(arr1, arr2, arr3)
if len(common) == 0:
print(-1)
# Print the result
print(*common)
C#
// C# Code to find common elements in three sorted arrays
using System;
using System.Collections.Generic;
public class GfG {
// Function to find common elements in three arrays.
static List<int> CommonElements(List<int> arr1,
List<int> arr2,
List<int> arr3)
{
// Dictionary to mark the common elements
Dictionary<int, int> mp
= new Dictionary<int, int>();
// Mark all the elements in the first array with
// value=1
foreach(int ele in arr1) { mp[ele] = 1; }
// Mark all the elements which are common in first
// and second array with value = 2
foreach(int ele in arr2)
{
if (mp.ContainsKey(ele) && mp[ele] == 1)
mp[ele] = 2;
}
// Mark all the elements which are common in first,
// second and third array with value = 3
foreach(int ele in arr3)
{
if (mp.ContainsKey(ele) && mp[ele] == 2)
mp[ele] = 3;
}
// Store all the common elements
List<int> commonElements = new List<int>();
foreach(var ele in mp)
{
if (ele.Value == 3)
commonElements.Add(ele.Key);
}
// Return the common elements which are common in
// all the three sorted arrays
commonElements.Sort();
return commonElements;
}
public static void Main(string[] args)
{
// Sample Input
List<int> arr1 = new List<int>{ 1, 5, 10, 20, 30 };
List<int> arr2 = new List<int>{ 5, 13, 15, 20 };
List<int> arr3 = new List<int>{ 5, 20 };
List<int> common = CommonElements(arr1, arr2, arr3);
if (common.Count == 0)
Console.Write(-1);
foreach(int num in common)
{
Console.Write(num + " ");
}
}
}
JavaScript
function commonElements(arr1, arr2, arr3)
{
// Map to mark the common elements
let mp = new Map();
// Mark all the elements in the first array with value=1
arr1.forEach(ele => { mp.set(ele, 1); });
// Mark all the elements which are common in first and
// second array with value = 2
arr2.forEach(ele => {
if (mp.has(ele) && mp.get(ele) === 1) {
mp.set(ele, 2);
}
});
// Mark all the elements which are common in first,
// second and third array with value = 3
arr3.forEach(ele => {
if (mp.has(ele) && mp.get(ele) === 2) {
mp.set(ele, 3);
}
});
let commonElements = [];
mp.forEach((value, key) => {
if (value === 3) {
commonElements.push(key);
}
});
return commonElements;
}
// Sample Input
let arr1 = [ 1, 5, 10, 20, 30 ];
let arr2 = [ 5, 13, 15, 20 ];
let arr3 = [ 5, 20 ];
let common = commonElements(arr1, arr2, arr3);
if (common.length == 0)
console.log(-1);
console.log(common.join(" "));
Time complexity: O((n1 + n2 + n3)*log n1), where inserting arr1[] takes O(n1 * log(n1)), and lookups for arr2[] and arr3[] take O(n2 * log(n1) + n3 * log(n1))
Auxiliary Space: O(n1)
[Expected Approach] Using three pointers - O(n1 + n2 + n3) Time and O(1) Space
We can efficiently find common elements in three sorted arrays using the three-pointer technique, eliminating the need for merging or intersecting the arrays.
Since the arrays are sorted in non-decreasing order, the smallest element among the three pointers at any moment will always be the smallest in the merged arrays. Leveraging this property, we can optimize our approach as follows:
- Initialize three pointers, one for each array.
- Compare the current elements at each pointer.
- If they are equal, it's a common element, store it and move all three pointers forward.
- Otherwise, move only the pointer pointing to the smallest element.
- Repeat the process until at least one array is fully traversed.
Working of Three pointers approach:
C++
#include <bits/stdc++.h>
using namespace std;
vector<int> commonElements(vector<int> arr1, vector<int> arr2, vector<int> arr3)
{
int i = 0, j = 0, k = 0;
int n1 = arr1.size(), n2 = arr2.size(), n3 = arr3.size();
vector<int> common;
while (i < n1 && j < n2 && k < n3)
{
if (arr1[i] == arr2[j] && arr2[j] == arr3[k])
{
common.push_back(arr1[i]);
i++;
j++;
k++;
while (i < n1 && arr1[i] == arr1[i - 1])
i++;
while (j < n2 && arr2[j] == arr2[j - 1])
j++;
while (k < n3 && arr3[k] == arr3[k - 1])
k++;
}
else if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr3[k])
j++;
else
k++;
}
return common;
}
int main()
{
vector<int> arr1 = {1, 5, 10, 20, 30};
vector<int> arr2 = {5, 13, 15, 20};
vector<int> arr3 = {5, 20};
vector<int> common = commonElements(arr1, arr2, arr3);
if (common.size() == 0)
cout << -1;
for (int ele : common)
{
cout << ele << " ";
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
public class GfG {
static List<Integer>
commonElements(int[] arr1, int[] arr2, int[] arr3)
{
int i = 0, j = 0, k = 0;
List<Integer> common = new ArrayList<>();
while (i < arr1.length && j < arr2.length
&& k < arr3.length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
common.add(arr1[i]);
i++;
j++;
k++;
while (i < arr1.length
&& arr1[i] == arr1[i - 1])
i++;
while (j < arr2.length
&& arr2[j] == arr2[j - 1])
j++;
while (k < arr3.length
&& arr3[k] == arr3[k - 1])
k++;
}
else if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr3[k])
j++;
else
k++;
}
return common;
}
public static void main(String[] args)
{
int[] arr1 = { 1, 5, 10, 20, 30 };
int[] arr2 = { 5, 13, 15, 20 };
int[] arr3 = { 5, 20 };
List<Integer> common
= commonElements(arr1, arr2, arr3);
if (common.size() == 0)
System.out.print(-1);
for (int i = 0; i < common.size(); i++)
System.out.print(common.get(i) + " ");
}
}
Python
# Function to find common elements in three arrays
def commonElements(arr1, arr2, arr3):
i, j, k = 0, 0, 0
common = []
while i < len(arr1) and j < len(arr2) and k < len(arr3):
if arr1[i] == arr2[j] == arr3[k]:
common.append(arr1[i])
i += 1
j += 1
k += 1
while i < len(arr1) and arr1[i] == arr1[i - 1]:
i += 1
while j < len(arr2) and arr2[j] == arr2[j - 1]:
j += 1
while k < len(arr3) and arr3[k] == arr3[k - 1]:
k += 1
elif arr1[i] < arr2[j]:
i += 1
elif arr2[j] < arr3[k]:
j += 1
else:
k += 1
return common
# Sample Input
arr1 = [1, 5, 10, 20, 30]
arr2 = [5, 13, 15, 20]
arr3 = [5, 20]
common = commonElements(arr1, arr2, arr3)
if len(common) == 0:
print(-1)
print(*common)
C#
using System;
using System.Collections.Generic;
class GfG {
static List<int> commonElements(int[] arr1, int[] arr2,
int[] arr3)
{
int i = 0, j = 0, k = 0;
List<int> common = new List<int>();
while (i < arr1.Length && j < arr2.Length
&& k < arr3.Length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
common.Add(arr1[i]);
i++;
j++;
k++;
while (i < arr1.Length
&& arr1[i] == arr1[i - 1])
i++;
while (j < arr2.Length
&& arr2[j] == arr2[j - 1])
j++;
while (k < arr3.Length
&& arr3[k] == arr3[k - 1])
k++;
}
else if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr3[k])
j++;
else
k++;
}
return common;
}
static void Main()
{
int[] arr1 = { 1, 5, 10, 20, 30 };
int[] arr2 = { 5, 13, 15, 20 };
int[] arr3 = { 5, 20 };
List<int> common = commonElements(arr1, arr2, arr3);
if (common.Count == 0)
Console.Write(-1);
Console.WriteLine(string.Join(" ", common));
}
}
JavaScript
// Function to find common elements in three arrays
function commonElements(arr1, arr2, arr3)
{
let i = 0, j = 0, k = 0;
let common = [];
while (i < arr1.length && j < arr2.length
&& k < arr3.length) {
if (arr1[i] === arr2[j] && arr2[j] === arr3[k]) {
common.push(arr1[i]);
i++;
j++;
k++;
while (i < arr1.length
&& arr1[i] === arr1[i - 1])
i++;
while (j < arr2.length
&& arr2[j] === arr2[j - 1])
j++;
while (k < arr3.length
&& arr3[k] === arr3[k - 1])
k++;
}
else if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr3[k])
j++;
else
k++;
}
return common;
}
// Driver code
function main()
{
let arr1 = [ 1, 5, 10, 20, 30 ];
let arr2 = [ 5, 13, 15, 20 ];
let arr3 = [ 5, 20 ];
let common = commonElements(arr1, arr2, arr3);
if (common.length == 0)
console.log(-1);
console.log(common.join(" "));
}
main();
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