# Find common elements in three sorted arrays

Given three Sorted arrays 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

Recommended Practice

## Common elements in three sorted arrays using two pointer:

A simple solution is to first find the intersection of two arrays and store the intersection in a temporary array, then find the intersection of the third array and temporary array.

• Initialize both pointers i and j to 0, and an empty list common.
• While both pointers i and j are within the bounds of the two arrays:
• If arr1[i] is less than arr2[j], increment i by 1.
• If arr2[j] is less than arr1[i], increment j by 1.
• If arr1[i] is equal to arr2[j]:
• Add arr1[i] to the common list.
• Increment both i and j by 1.
• Return the common list containing the common elements of the two arrays.

Below is the implementation of the above approach:

## C++

 `#include ``using` `namespace` `std;` `// Function to find the intersection of two arrays``void` `FindIntersection(``int` `arr1[], ``int` `arr2[], ``int` `temp[],``                      ``int` `m, ``int` `n, ``int``& k)``{``    ``int` `i = 0, j = 0;``    ``// vector to store the intersection of the arr1[] and``    ``// arr2[]``    ``while` `(i < m && j < n) {``        ``// ith element can not be common element``        ``if` `(arr1[i] < arr2[j]) {``            ``i++;``        ``}` `        ``// jth element can not be common element``        ``else` `if` `(arr2[j] < arr1[i]) {``            ``j++;``        ``}` `        ``// if arr1[i] == arr2[j]``        ``else` `{``            ``temp[k] = arr1[i];``            ``i++;``            ``j++;``            ``k++;``        ``}``    ``}``}` `int` `main()``{` `    ``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 };``    ``int` `n1 = ``sizeof``(arr1) / ``sizeof``(arr1[0]);``    ``int` `n2 = ``sizeof``(arr2) / ``sizeof``(arr2[0]);``    ``int` `n3 = ``sizeof``(arr3) / ``sizeof``(arr3[0]);` `    ``// temp array to store the common elements of arr1 and``    ``// arr2 arrays``    ``int` `temp[200000];` `    ``// ans array to store the common elements of temp and``    ``// arr3 arrays (i.e common elements of all 3 arrays)``    ``int` `ans[200000];` `    ``int` `k = 0;` `    ``// function call to find the temp array``    ``FindIntersection(arr1, arr2, temp, n1, n2, k);``    ``int` `tempSize = k;``    ``k = 0;` `    ``// function call to find the ans array.``    ``FindIntersection(arr3, temp, ans, n3, tempSize, k);``    ``cout << ``"Common elements present in arrays are : \n"``;` `    ``for` `(``int` `i = 0; i < k; i++) {``        ``cout << ans[i] << ``" "``;``    ``}``    ``cout << endl;` `    ``return` `0;``}` `// This code is contributed by Hem Kishan`

## Java

 `/*package whatever //do not write package name here */` `import` `java.io.*;` `public` `class` `GFG {` `    ``// Function to find the intersection of two arrays``    ``static` `void` `findIntersection(``int``[] arr1, ``int``[] arr2,``                                 ``int``[] temp, ``int` `m, ``int` `n,``                                 ``int``[] k)``    ``{``        ``int` `i = ``0``, j = ``0``;``        ``// Loop to find the intersection of arr1[] and``        ``// arr2[]``        ``while` `(i < m && j < n) {``            ``// ith element can't be a common element``            ``if` `(arr1[i] < arr2[j]) {``                ``i++;``            ``}``            ``// jth element can't be a common element``            ``else` `if` `(arr2[j] < arr1[i]) {``                ``j++;``            ``}``            ``// if arr1[i] == arr2[j]``            ``else` `{``                ``temp[k[``0``]] = arr1[i];``                ``i++;``                ``j++;``                ``k[``0``]++;``            ``}``        ``}``    ``}` `    ``public` `static` `void` `main(String[] args)``    ``{` `        ``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` `};``        ``int` `n1 = arr1.length;``        ``int` `n2 = arr2.length;``        ``int` `n3 = arr3.length;` `        ``// temp array to store the common elements of arr1``        ``// and arr2 arrays``        ``int``[] temp = ``new` `int``[``200000``];` `        ``// ans array to store the common elements of temp``        ``// and arr3 arrays``        ``int``[] ans = ``new` `int``[``200000``];` `        ``int``[] k = {``            ``0``        ``}; ``// Mutable integer to simulate pass-by-reference` `        ``// function call to find the temp array``        ``findIntersection(arr1, arr2, temp, n1, n2, k);``        ``int` `tempSize = k[``0``];``        ``k[``0``] = ``0``;` `        ``// function call to find the ans array``        ``findIntersection(arr3, temp, ans, n3, tempSize, k);` `        ``System.out.println(``            ``"Common elements present in arrays are :"``);` `        ``// Printing the common elements``        ``for` `(``int` `i = ``0``; i < k[``0``]; i++) {``            ``System.out.print(ans[i] + ``" "``);``        ``}``        ``System.out.println();``    ``}``}`

## Python3

 `# Function to find the intersection of two arrays``def` `find_intersection(arr1, arr2, temp, m, n, k):``    ``i ``=` `0``    ``j ``=` `0``    ``while` `i < m ``and` `j < n:``        ``if` `arr1[i] < arr2[j]:``            ``i ``+``=` `1``        ``elif` `arr2[j] < arr1[i]:``            ``j ``+``=` `1``        ``else``:``            ``temp[k[``0``]] ``=` `arr1[i]``            ``i ``+``=` `1``            ``j ``+``=` `1``            ``k[``0``] ``+``=` `1` `# Main function`  `def` `main():``    ``arr1 ``=` `[``1``, ``5``, ``10``, ``20``, ``40``, ``80``]``    ``arr2 ``=` `[``6``, ``7``, ``20``, ``80``, ``100``]``    ``arr3 ``=` `[``3``, ``4``, ``15``, ``20``, ``30``, ``70``, ``80``, ``120``]``    ``n1 ``=` `len``(arr1)``    ``n2 ``=` `len``(arr2)``    ``n3 ``=` `len``(arr3)` `    ``temp ``=` `[``0``] ``*` `200000``    ``ans ``=` `[``0``] ``*` `200000` `    ``k ``=` `[``0``]  ``# Mutable list to simulate pass-by-reference` `    ``# Function call to find the temp array``    ``find_intersection(arr1, arr2, temp, n1, n2, k)``    ``temp_size ``=` `k[``0``]``    ``k[``0``] ``=` `0` `    ``# Function call to find the ans array``    ``find_intersection(arr3, temp, ans, n3, temp_size, k)` `    ``print``(``"Common elements present in arrays are:"``)` `    ``# Printing the common elements``    ``for` `i ``in` `range``(k[``0``]):``        ``print``(ans[i], end``=``" "``)``    ``print``()`  `if` `__name__ ``=``=` `"__main__"``:``    ``main()`

## C#

 `using` `System;` `public` `class` `GFG {``    ``// Function to find the intersection of two arrays``    ``static` `void` `FindIntersection(``int``[] arr1, ``int``[] arr2,``                                 ``int``[] temp, ``int` `m, ``int` `n,``                                 ``int``[] k)``    ``{``        ``int` `i = 0, j = 0;``        ``// Loop to find the intersection of arr1[] and``        ``// arr2[]``        ``while` `(i < m && j < n) {``            ``// ith element can't be a common element``            ``if` `(arr1[i] < arr2[j]) {``                ``i++;``            ``}``            ``// jth element can't be a common element``            ``else` `if` `(arr2[j] < arr1[i]) {``                ``j++;``            ``}``            ``// if arr1[i] == arr2[j]``            ``else` `{``                ``temp[k[0]] = arr1[i];``                ``i++;``                ``j++;``                ``k[0]++;``            ``}``        ``}``    ``}` `    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``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 };``        ``int` `n1 = arr1.Length;``        ``int` `n2 = arr2.Length;``        ``int` `n3 = arr3.Length;` `        ``// temp array to store the common elements of arr1``        ``// and arr2 arrays``        ``int``[] temp = ``new` `int``[200000];` `        ``// ans array to store the common elements of temp``        ``// and arr3 arrays``        ``int``[] ans = ``new` `int``[200000];` `        ``int``[] k = {``            ``0``        ``}; ``// Mutable integer to simulate pass-by-reference` `        ``// Function call to find the temp array``        ``FindIntersection(arr1, arr2, temp, n1, n2, k);``        ``int` `tempSize = k[0];``        ``k[0] = 0;` `        ``// Function call to find the ans array``        ``FindIntersection(arr3, temp, ans, n3, tempSize, k);` `        ``Console.WriteLine(``            ``"Common elements present in arrays are :"``);` `        ``// Printing the common elements``        ``for` `(``int` `i = 0; i < k[0]; i++) {``            ``Console.Write(ans[i] + ``" "``);``        ``}``        ``Console.WriteLine();``    ``}``}`

## Javascript

 `// Function to find the intersection of two arrays``function` `findIntersection(arr1, arr2) {``    ``let i = 0;``    ``let j = 0;``    ``const temp = [];` `    ``while` `(i < arr1.length && j < arr2.length) {``        ``if` `(arr1[i] < arr2[j]) {``            ``i++;``        ``} ``else` `if` `(arr2[j] < arr1[i]) {``            ``j++;``        ``} ``else` `{``            ``temp.push(arr1[i]);``            ``i++;``            ``j++;``        ``}``    ``}` `    ``return` `temp;``}` `function` `main() {``    ``const arr1 = [1, 5, 10, 20, 40, 80];``    ``const arr2 = [6, 7, 20, 80, 100];``    ``const arr3 = [3, 4, 15, 20, 30, 70, 80, 120];` `    ``// Find the intersection of arr1 and arr2``    ``const temp = findIntersection(arr1, arr2);` `    ``// Find the intersection of temp and arr3 to get common elements``    ``const ans = findIntersection(temp, arr3);` `    ``console.log(``"Common elements present in arrays are:"``);``    ``for` `(const element of ans) {``        ``console.log(element);``    ``}``}` `// Call the main function to start the program``main();`

Output
```Common elements present in arrays are :
20 80

```

Time complexity: O(n1 + n2 + n3), where n1, n2 and n3 are sizes of ar1[], ar2[] and ar3[] respectively.
Auxiliary Space: O(max(n1,n2,n3))

## Common elements in three sorted arrays using three pointer:

It is known that the arrays are sorted in a non-decreasing order. When a common integer has been found, we want to move forward in each array in search of another common integer. Otherwise, the smaller integer among the three must not be common.

The reason for this is that at least one of the other integers is a larger integer, and as we move forward in the array, we only encounter larger integers. In this case, we want to proceed with only the array that contains the smaller integer.

• Create and initialize three variables i, j, and k with 0, it will point to the indices of the arrays.
• Repeat the following steps until we reach the end of any one of the arrays:
• Check whether the integers appointed by i, j, and k are equal or not.
• If they are equal, print any of the integers and increase i, j, and k by 1.
• Otherwise, increase the index that points to the smaller integer by 1.

Illustration:

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[0]);``    ``int` `n2 = ``sizeof``(ar2) / ``sizeof``(ar2[0]);``    ``int` `n3 = ``sizeof``(ar3) / ``sizeof``(ar3[0]);` `    ``cout << ``"Common Elements are "``;``    ``findCommon(ar1, ar2, ar3, n1, n2, n3);``    ``return` `0;``}` `// This code is contributed by Sania Kumari Gupta``// (kriSania804)`

## C

 `// C program to print common elements in three arrays``#include ` `// 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]) {``            ``printf``(``"%d "``, 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[0]);``    ``int` `n2 = ``sizeof``(ar2) / ``sizeof``(ar2[0]);``    ``int` `n3 = ``sizeof``(ar3) / ``sizeof``(ar3[0]);` `    ``printf``(``"Common Elements are "``);``    ``findCommon(ar1, ar2, ar3, n1, n2, n3);``    ``return` `0;``}` `// This code is contributed by Sania Kumari Gupta``// (kriSania804)`

## Java

 `// Java program to find common elements in three arrays``import` `java.io.*;``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.`

## Javascript

 ``

## 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.``?>`

Output
```Common Elements are 20 80

```

Time complexity: O(n1 + n2 + n3), In the worst case, the largest-sized array may have all small elements and the middle-sized array has all middle elements.
Auxiliary Space:  O(1)