Related Articles

# Find common elements in three sorted arrays

• Difficulty Level : Easy
• Last Updated : 07 Jul, 2021

Given three arrays sorted in non-decreasing order, print all common elements in these arrays.

Examples:

Input
ar1[] = {1, 5, 10, 20, 40, 80}
ar2[] = {6, 7, 20, 80, 100}
ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20, 80

Input
ar1[] = {1, 5, 5}
ar2[] = {3, 4, 5, 5, 10}
ar3[] = {5, 5, 10, 20}
Output: 5, 5

A simple solution is to first find intersection of two arrays and store the intersection in a temporary array, then find the intersection of third array and temporary array.
Time complexity of this solution is O(n1 + n2 + n3) where n1, n2 and n3 are sizes of ar1[], ar2[] and ar3[] respectively.
The above solution requires extra space and two loops, we can find the common elements using a single loop and without extra space. The idea is similar to intersection of two arrays. Like two arrays loop, we run a loop and traverse three arrays.
Let the current element traversed in ar1[] be x, in ar2[] be y and in ar3[] be z. We can have following cases inside the loop.

• If x, y and z are same, we can simply print any of them as common element and move ahead in all three arrays.
• Else If x < y, we can move ahead in ar1[] as x cannot be a common element.
• Else If x > z and y > z), we can simply move ahead in ar3[] as z cannot be a common element.

Below image is a dry run of the above approach: Below is the implementation of the above approach:

## C++

 `// C++ program to print common elements in three arrays``#include ``using` `namespace` `std;` `// This function prints common elements in ar1``void` `findCommon(``int` `ar1[], ``int` `ar2[], ``int` `ar3[], ``int` `n1, ``int` `n2, ``int` `n3)``{``    ``// Initialize starting indexes for ar1[], ar2[] and ar3[]``    ``int` `i = 0, j = 0, k = 0;` `    ``// Iterate through three arrays while all arrays have elements``    ``while` `(i < n1 && j < n2 && k < n3)``    ``{``         ``// If x = y and y = z, print any of them and move ahead``         ``// in all arrays``         ``if` `(ar1[i] == ar2[j] && ar2[j] == ar3[k])``         ``{   cout << ar1[i] << ``" "``;   i++; j++; k++; }` `         ``// x < y``         ``else` `if` `(ar1[i] < ar2[j])``             ``i++;` `         ``// y < z``         ``else` `if` `(ar2[j] < ar3[k])``             ``j++;` `         ``// We reach here when x > y and z < y, i.e., z is smallest``         ``else``             ``k++;``    ``}``}` `// Driver code``int` `main()``{``    ``int` `ar1[] = {1, 5, 10, 20, 40, 80};``    ``int` `ar2[] = {6, 7, 20, 80, 100};``    ``int` `ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};``    ``int` `n1 = ``sizeof``(ar1)/``sizeof``(ar1);``    ``int` `n2 = ``sizeof``(ar2)/``sizeof``(ar2);``    ``int` `n3 = ``sizeof``(ar3)/``sizeof``(ar3);` `    ``cout << ``"Common Elements are "``;``    ``findCommon(ar1, ar2, ar3, n1, n2, n3);``    ``return` `0;``}`

## Java

 `// Java program to find common elements in three arrays``class` `FindCommon``{``    ``// This function prints common elements in ar1``    ``void` `findCommon(``int` `ar1[], ``int` `ar2[], ``int` `ar3[])``    ``{``        ``// Initialize starting indexes for ar1[], ar2[] and ar3[]``        ``int` `i = ``0``, j = ``0``, k = ``0``;` `        ``// Iterate through three arrays while all arrays have elements``        ``while` `(i < ar1.length && j < ar2.length && k < ar3.length)``        ``{``             ``// If x = y and y = z, print any of them and move ahead``             ``// in all arrays``             ``if` `(ar1[i] == ar2[j] && ar2[j] == ar3[k])``             ``{   System.out.print(ar1[i]+``" "``);   i++; j++; k++; }` `             ``// x < y``             ``else` `if` `(ar1[i] < ar2[j])``                 ``i++;` `             ``// y < z``             ``else` `if` `(ar2[j] < ar3[k])``                 ``j++;` `             ``// We reach here when x > y and z < y, i.e., z is smallest``             ``else``                 ``k++;``        ``}``    ``}` `    ``// Driver code to test above``    ``public` `static` `void` `main(String args[])``    ``{``        ``FindCommon ob = ``new` `FindCommon();` `        ``int` `ar1[] = {``1``, ``5``, ``10``, ``20``, ``40``, ``80``};``        ``int` `ar2[] = {``6``, ``7``, ``20``, ``80``, ``100``};``        ``int` `ar3[] = {``3``, ``4``, ``15``, ``20``, ``30``, ``70``, ``80``, ``120``};` `        ``System.out.print(``"Common elements are "``);``        ``ob.findCommon(ar1, ar2, ar3);``    ``}``}` `/*This code is contributed by Rajat Mishra */`

## Python

 `# Python function to print common elements in three sorted arrays``def` `findCommon(ar1, ar2, ar3, n1, n2, n3):``    ` `    ``# Initialize starting indexes for ar1[], ar2[] and ar3[]``    ``i, j, k ``=` `0``, ``0``, ``0``    ` `    ``# Iterate through three arrays while all arrays have elements   ``    ``while` `(i < n1 ``and` `j < n2 ``and` `k< n3):``        ` `        ``# If x = y and y = z, print any of them and move ahead``        ``# in all arrays``        ``if` `(ar1[i] ``=``=` `ar2[j] ``and` `ar2[j] ``=``=` `ar3[k]):``            ``print` `ar1[i],``            ``i ``+``=` `1``            ``j ``+``=` `1``            ``k ``+``=` `1``        ` `        ``# x < y   ``        ``elif` `ar1[i] < ar2[j]:``            ``i ``+``=` `1``            ` `        ``# y < z   ``        ``elif` `ar2[j] < ar3[k]:``            ``j ``+``=` `1``        ` `        ``# We reach here when x > y and z < y, i.e., z is smallest   ``        ``else``:``            ``k ``+``=` `1` `# Driver program to check above function``ar1 ``=` `[``1``, ``5``, ``10``, ``20``, ``40``, ``80``]``ar2 ``=` `[``6``, ``7``, ``20``, ``80``, ``100``]``ar3 ``=` `[``3``, ``4``, ``15``, ``20``, ``30``, ``70``, ``80``, ``120``]``n1 ``=` `len``(ar1)``n2 ``=` `len``(ar2)``n3 ``=` `len``(ar3)``print` `"Common elements are"``,``findCommon(ar1, ar2, ar3, n1, n2, n3)` `# This code is contributed by __Devesh Agrawal__`

## C#

 `// C# program to find common elements in``// three arrays``using` `System;` `class` `GFG {``    ` `    ``// This function prints common element``    ``// s in ar1``    ``static` `void` `findCommon(``int` `[]ar1, ``int` `[]ar2,``                                      ``int` `[]ar3)``    ``{``        ` `        ``// Initialize starting indexes for``        ``// ar1[], ar2[] and ar3[]``        ``int` `i = 0, j = 0, k = 0;` `        ``// Iterate through three arrays while``        ``// all arrays have elements``        ``while` `(i < ar1.Length && j < ar2.Length``                              ``&& k < ar3.Length)``        ``{``            ` `            ``// If x = y and y = z, print any of``            ``// them and move ahead in all arrays``            ``if` `(ar1[i] == ar2[j] &&``                               ``ar2[j] == ar3[k])``            ``{``                ``Console.Write(ar1[i] + ``" "``);``                ``i++;``                ``j++;``                ``k++;``            ``}` `            ``// x < y``            ``else` `if` `(ar1[i] < ar2[j])``                ``i++;` `            ``// y < z``            ``else` `if` `(ar2[j] < ar3[k])``                ``j++;` `            ``// We reach here when x > y and``            ``// z < y, i.e., z is smallest``            ``else``                ``k++;``        ``}``    ``}` `    ``// Driver code to test above``    ``public` `static` `void` `Main()``    ``{``        ` `        ``int` `[]ar1 = {1, 5, 10, 20, 40, 80};``        ``int` `[]ar2 = {6, 7, 20, 80, 100};``        ``int` `[]ar3 = {3, 4, 15, 20, 30,``                             ``70, 80, 120};` `        ``Console.Write(``"Common elements are "``);``        ` `        ``findCommon(ar1, ar2, ar3);``    ``}``}` `// This code is contributed by Sam007.`

## PHP

 ` y and``        ``// z < y, i.e., z is smallest``        ``else``            ``\$k``++;``    ``}``}` `// Driver program to test above function``    ``\$ar1` `= ``array``(1, 5, 10, 20, 40, 80);``    ``\$ar2` `= ``array``(6, 7, 20, 80, 100);``    ``\$ar3` `= ``array``(3, 4, 15, 20, 30, 70,``                                ``80, 120);``    ``\$n1` `= ``count``(``\$ar1``);``    ``\$n2` `= ``count``(``\$ar2``);``    ``\$n3` `= ``count``(``\$ar3``);` `    ``echo` `"Common Elements are "``;``    ` `    ``findCommon(``\$ar1``, ``\$ar2``, ``\$ar3``,``\$n1``, ``\$n2``, ``\$n3``);``    ` `// This code is contributed by anuj_67.``?>`

## Javascript

 ``
Output
`Common Elements are 20 80 `

Time complexity of the above solution is O(n1 + n2 + n3). In the worst case, the largest sized array may have all small elements and middle-sized array has all middle elements.

Method 2:

The approach used above works well if the arrays does not contain duplicate values however it can fail in cases where the array elements are repeated. This can lead to a single common element to get printed multiple times.

These duplicate entries can be handled without using any additional data structure by keeping the track of the previous element. Since the elements inside the array are arranged in sorted manner there is no possibility for the repeated elements to occur at random positions.

Let’s consider the current element traversed in ar1[] be x, in ar2[] be y and in ar3[] be z and let the variables prev1, prev2, prev3 for keeping the track of last encountered element in each array and initialize them with INT_MIN. Hence for every element we visit across each array, we check for the following.

• If x = prev1, move ahead in ar1[] and repeat the procedure until x != prev1. Similarly apply the same for the ar2[] and ar3[].
• If x, y and z are same, we can simply print any of them as common element ,update prev1, prev2 and prev3 and move ahead in all three arrays.
• Else If (x < y), we update prev1 and move ahead in ar1[] as x cannot be a common element.
• Else If (y < z), we update prev2 and move ahead in ar2[] as y cannot be a common element.
• Else If (x > z and y > z), we update prev3 and we move ahead in ar3[] as z cannot be a common element.

Below is the implementation of the above approach:

## C++

 `// C++ program to print common``// elements in three arrays``#include ``using` `namespace` `std;` `// This function prints``// common elements in ar1``void` `findCommon(``int` `ar1[], ``int` `ar2[], ``int` `ar3[], ``int` `n1,``                ``int` `n2, ``int` `n3)``{``    ` `    ``// Initialize starting indexes``    ``// for ar1[], ar2[] and``    ``// ar3[]``    ``int` `i = 0, j = 0, k = 0;` `    ``// Declare three variables prev1,``    ``// prev2, prev3 to track``    ``// previous element``    ``int` `prev1, prev2, prev3;` `    ``// Initialize prev1, prev2,``    ``// prev3 with INT_MIN``    ``prev1 = prev2 = prev3 = INT_MIN;` `    ``// Iterate through three arrays``    ``// while all arrays have``    ``// elements``    ``while` `(i < n1 && j < n2 && k < n3) {``      ` `        ``// If ar1[i] = prev1 and i < n1,``        ``// keep incrementing i``        ``while` `(ar1[i] == prev1 && i < n1)``            ``i++;` `        ``// If ar2[j] = prev2 and j < n2,``        ``// keep incrementing j``        ``while` `(ar2[j] == prev2 && j < n2)``            ``j++;` `        ``// If ar3[k] = prev3 and k < n3,``        ``// keep incrementing k``        ``while` `(ar3[k] == prev3 && k < n3)``            ``k++;` `        ``// If x = y and y = z, print``        ``// any of them, update``        ``// prev1 prev2, prev3 and move``        ``//ahead in each array``        ``if` `(ar1[i] == ar2[j] && ar2[j] == ar3[k]) {``            ``cout << ar1[i] << ``" "``;``            ``prev1 = ar1[i];``            ``prev2 = ar2[j];``            ``prev3 = ar3[k];``            ``i++;``            ``j++;``            ``k++;``        ``}` `        ``// If x < y, update prev1``        ``// and increment i``        ``else` `if` `(ar1[i] < ar2[j]) {``            ``prev1 = ar1[i];``            ``i++;``        ``}` `        ``// If y < z, update prev2``        ``// and increment j``        ``else` `if` `(ar2[j] < ar3[k]) {``            ``prev2 = ar2[j];``            ``j++;``        ``}` `        ``// We reach here when x > y``        ``// and z < y, i.e., z is``        ``// smallest update prev3``        ``// and imcrement k``        ``else` `{``            ``prev3 = ar3[k];``            ``k++;``        ``}``    ``}``}` `// Driver code``int` `main()``{``    ``int` `ar1[] = { 1, 5, 10, 20, 40, 80, 80 };``    ``int` `ar2[] = { 6, 7, 20, 80, 80, 100 };``    ``int` `ar3[] = { 3, 4, 15, 20, 30, 70, 80, 80, 120 };``    ``int` `n1 = ``sizeof``(ar1) / ``sizeof``(ar1);``    ``int` `n2 = ``sizeof``(ar2) / ``sizeof``(ar2);``    ``int` `n3 = ``sizeof``(ar3) / ``sizeof``(ar3);` `    ``cout << ``"Common Elements are "``;``    ``findCommon(ar1, ar2, ar3, n1, n2, n3);``    ``return` `0;``}`

## Javascript

 ``
Output
`Common Elements are 20 80 `

Time Complexity for the above approach still remains O(n1 + n2 + n3) and space complexity also remains O(1) and no extra space and data structure is required to handle the duplicate array entries.

Method 3:

In this approach, we will first delete the duplicate from each array, and after this, we will find the frequency of each element and the element whose frequency equals 3 will be printed. For finding the frequency we can use a map but in this, we will use an array instead of a map. But the problem with using an array is, we cannot find the frequency of negative numbers so in the code given below we will consider each and every element of array to be positive.

## Java

 `// Java implementation of the above approach` `class` `GFG {``    ``public` `static` `void` `commonElements(``int``[] arr1,``                                      ``int``[] arr2,``                                      ``int``[] arr3, ``int` `n1,``                                      ``int` `n2, ``int` `n3)``    ``{``        ``// creating a max variable``        ``// for storing the maximum``        ``// value present in the all``        ``// the three array``        ``// this will be the size of``        ``// array for calculating the``        ``// frequency of each element``        ``// present in all the array``        ``int` `max = Integer.MIN_VALUE;` `        ``// deleting duplicates in linear time``        ``// for arr1``        ``int` `res1 = ``1``;``        ``for` `(``int` `i = ``1``; i < n1; i++)``        ``{``            ``max = Math.max(arr1[i], max);``            ``if` `(arr1[i] != arr1[res1 - ``1``])``            ``{``                ``arr1[res1] = arr1[i];``                ``res1++;``            ``}``        ``}` `        ``// deleting duplicates in linear time``        ``// for arr2``        ``int` `res2 = ``1``;``        ``for` `(``int` `i = ``1``; i < n2; i++)``        ``{``            ``max = Math.max(arr2[i], max);``            ``if` `(arr2[i] != arr2[res2 - ``1``])``            ``{``                ``arr2[res2] = arr2[i];``                ``res2++;``            ``}``        ``}` `        ``// deleting duplicates in linear time``        ``// for arr3``        ``int` `res3 = ``1``;``        ``for` `(``int` `i = ``1``; i < n3; i++)``        ``{``            ``max = Math.max(arr3[i], max);``            ``if` `(arr3[i] != arr3[res3 - ``1``])``            ``{``                ``arr3[res3] = arr3[i];``                ``res3++;``            ``}``        ``}` `        ``// creating an array for finding frequency``        ``int``[] freq = ``new` `int``[max + ``1``];` `        ``// calculating the frequency of``        ``// all the elements present in``        ``// all the array``        ``for` `(``int` `i = ``0``; i < res1; i++)``            ``freq[arr1[i]]++;``        ``for` `(``int` `i = ``0``; i < res2; i++)``            ``freq[arr2[i]]++;``        ``for` `(``int` `i = ``0``; i < res3; i++)``            ``freq[arr3[i]]++;` `        ``// iterating till max and``        ``// whenever the frequency of element``        ``// will be three we print that element``        ``for` `(``int` `i = ``0``; i <= max; i++)``            ``if` `(freq[i] == ``3``)``                ``System.out.print(i + ``" "``);``    ``}``  ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] arg)``    ``{` `        ``int` `arr1[] = { ``1``, ``5``, ``10``, ``20``, ``40``, ``80` `};``        ``int` `arr2[] = { ``6``, ``7``, ``20``, ``80``, ``100` `};``        ``int` `arr3[] = { ``3``, ``4``, ``15``, ``20``, ``30``, ``70``, ``80``, ``120` `};` `        ``commonElements(arr1, arr2, arr3, ``6``, ``5``, ``8``);``    ``}``}`
Output
`20 80 `

Method 4: Using STL

The idea is to use hash set. Here we use 2 of the sets to store elements of the 1st and 2nd array. The elements of the 3rd array are then checked if they are present in the first 2 sets. Then, we use a 3rd set to prevent any duplicates from getting added to the required array.

## C++

 `#include ``using` `namespace` `std;` `void` `findCommon(``int` `a[], ``int` `b[], ``int` `c[], ``int` `n1, ``int` `n2,``                ``int` `n3)``{``    ``// three sets to maintain frequency of elements``    ``unordered_set <``int``> uset,uset2,uset3;``    ``for``(``int` `i=0;i
Output
```Common Elements are
20
80```

Time Complexity: O(n1 + n2 + n3)
Space complexity: O(n1 + n2 + n3)