Find common elements in three sorted arrays - GeeksforGeeks

25 Apr, 2022
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++
Java
Python
C#
PHP
Javascript
// C++ program to print common elements in three arrays#include <bits/stdc++.h>using namespace std; // This function prints common elements in ar1void 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 codeint 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;}
// Java program to find common elements in three arraysclass 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 function to print common elements in three sorted arraysdef 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 functionar1 = [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# program to find common elements in// three arraysusing 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// PHP program to print common elements// in three arrays // This function prints common elements// in ar1function findCommon( $ar1, $ar2, $ar3,                         $n1, $n2, $n3){         // Initialize starting indexes for    // ar1[], ar2[] and ar3[]    $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])        {            echo $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 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.?>
<script>       // JavaScript program to print      // common elements in three arrays       // This function prints common elements in ar1      function findCommon(ar1, ar2, ar3, n1, n2, n3)      {               // Initialize starting indexes        // for ar1[], ar2[] and ar3[]        var 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])          {            document.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      var ar1 = [1, 5, 10, 20, 40, 80];      var ar2 = [6, 7, 20, 80, 100];      var ar3 = [3, 4, 15, 20, 30, 70, 80, 120];      var n1 = ar1.length;      var n2 = ar2.length;      var n3 = ar3.length;       document.write("Common Elements are ");      findCommon(ar1, ar2, ar3, n1, n2, n3);             // This code is contributed by rdtank.       </script>
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++
Java
Python3
C#
Javascript
// C++ program to print common// elements in three arrays#include <bits/stdc++.h>using namespace std; // This function prints// common elements in ar1void 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 codeint 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[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;}
// Java program to find common// elements in three arraysclass 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;        int n1 = ar1.length;        int n2 = ar2.length;        int n3 = ar3.length;         // Declare three variables prev1,        // prev2, prev3 to track previous        // element        int prev1, prev2, prev3;         // Initialize prev1, prev2,        // prev3 with INT_MIN        prev1 = prev2 = prev3 = Integer.MIN_VALUE;         while (i < n1 && j < n2 && k < n3) {             // If ar1[i] = prev1 and i < n1,            // keep incrementing i            while (i < n1 && ar1[i] == prev1)                i++;             // If ar2[j] = prev2 and j < n2,            // keep incrementing j            while (j < n2 && ar2[j] == prev2)                j++;             // If ar3[k] = prev3 and k < n3,            // keep incrementing k            while (k < n3 && ar3[k] == prev3)                k++;             if (i < n1 && j < n2 && k < n3) {                 // 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]) {                    System.out.print(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    public static void main(String args[])    {        FindCommon ob = new FindCommon();         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 };         System.out.print("Common elements are ");         ob.findCommon(ar1, ar2, ar3);    }} // This code is contributed by rajsanghavi9.
# Python 3 program for above approachimport sys # This function prints# common elements in ar1  def findCommon(ar1, ar2, ar3, n1,               n2, n3):     # Initialize starting indexes    # for ar1[], ar2and    # ar3[]    i = 0    j = 0    k = 0     # Declare three variables prev1,    # prev2, prev3 to track    # previous element    # Initialize prev1, prev2,    # prev3 with INT_MIN    prev1 = prev2 = prev3 = -sys.maxsize - 1     # Iterate through three arrays    # while all arrays have    # elements    while (i < n1 and j < n2 and k < n3):         # If ar1[i] = prev1 and i < n1,        # keep incrementing i        while (ar1[i] == prev1 and i < n1-1):            i += 1         # If ar2[j] = prev2 and j < n2,        # keep incrementing j        while (ar2[j] == prev2 and j < n2):            j += 1         # If ar3[k] = prev3 and k < n3,        # keep incrementing k        while (ar3[k] == prev3 and k < n3):            k += 1         # If x = y and y = z, pr        # any of them, update        # prev1 prev2, prev3 and move        # ahead in each array        if (ar1[i] == ar2[j] and ar2[j] == ar3[k]):            print(ar1[i], end=" ")            prev1 = ar1[i]            prev2 = ar2[j]            prev3 = ar3[k]            i += 1            j += 1            k += 1         # If x < y, update prev1        # and increment i        elif (ar1[i] < ar2[j]):            prev1 = ar1[i]            i += 1         # If y < z, update prev2        # and increment j        elif (ar2[j] < ar3[k]):            prev2 = ar2[j]            j += 1         # We reach here when x > y        # and z < y, i.e., z is        # smallest update prev3        # and imcrement k        else:            prev3 = ar3[k]            k += 1  # Driver codear1 = [1, 5, 10, 20, 40, 80, 80]ar2 = [6, 7, 20, 80, 80, 100]ar3 = [3, 4, 15, 20, 30, 70, 80, 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 splevel62.
// C# program to find common// elements in three arraysusing System;class GFG {     // This function prints common elements 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;        int n1 = ar1.Length;        int n2 = ar2.Length;        int n3 = ar3.Length;         // Declare three variables prev1,        // prev2, prev3 to track previous        // element        int prev1, prev2, prev3;         // Initialize prev1, prev2,        // prev3 with INT_MIN        prev1 = prev2 = prev3 = Int32.MinValue;         while (i < n1 && j < n2 && k < n3) {             // If ar1[i] = prev1 and i < n1,            // keep incrementing i            while (i < n1 && ar1[i] == prev1)                i++;             // If ar2[j] = prev2 and j < n2,            // keep incrementing j            while (j < n2 && ar2[j] == prev2)                j++;             // If ar3[k] = prev3 and k < n3,            // keep incrementing k            while (k < n3 && ar3[k] == prev3)                k++;             if (i < n1 && j < n2 && k < n3) {                 // 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]) {                    Console.Write(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    public static void Main()    {        // FindCommon ob = new FindCommon();        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 };         Console.Write("Common elements are ");         findCommon(ar1, ar2, ar3);    }} // This code is contributed by Samim Hossain Mondal.
<script> // Javascript program to print common// elements in three arrays // This function prints// common elements in ar1function findCommon(ar1, ar2, ar3, n1,                    n2, n3){         // Initialize starting indexes    // for ar1[], ar2[] and    // ar3[]    var i = 0, j = 0, k = 0;     // Declare three variables prev1,    // prev2, prev3 to track    // previous element    var prev1, prev2, prev3;     // Initialize prev1, prev2,    // prev3 with INT_MIN    prev1 = prev2 = prev3 = -1000000000;     // 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]) {            document.write(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 codevar ar1 = [ 1, 5, 10, 20, 40, 80, 80 ];var ar2 = [ 6, 7, 20, 80, 80, 100 ];var ar3 = [ 3, 4, 15, 20, 30, 70, 80, 80, 120 ];var n1 = ar1.length;var n2 = ar2.length;var n3 = ar3.length;document.write("Common Elements are ");findCommon(ar1, ar2, ar3, n1, n2, n3);  </script>
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
Python3
C#
Javascript
// 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);    }}
# Python implementation of the above approach   import sysdef commonElements(arr1,  arr2,  arr3 , n1 , n2 , 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    Max = -sys.maxsize -1     # deleting duplicates in linear time    # for arr1    res1 = 1    for i in range(1, n1):        Max = max(arr1[i], Max)        if arr1[i] != arr1[res1 - 1]:            arr1[res1] = arr1[i]            res1 += 1     # deleting duplicates in linear time    # for arr2    res2 = 1    for i in range(1, n2):        Max = max(arr2[i], Max)        if (arr2[i] != arr2[res2 - 1]):            arr2[res2] = arr2[i]            res2 += 1     # deleting duplicates in linear time    # for arr3    res3 = 1    for i in range(1, n3):        Max = max(arr3[i], Max)        if (arr3[i] != arr3[res3 - 1]):            arr3[res3] = arr3[i]            res3 += 1     # creating an array for finding frequency    freq = [0 for i in range(Max + 1)]     # calculating the frequency of    # all the elements present in    # all the array    for i in range(res1):        freq[arr1[i]] += 1    for i in range(res2):        freq[arr2[i]] += 1    for i in range(res3):        freq[arr3[i]] += 1     # iterating till max and    # whenever the frequency of element    # will be three we print that element    for i in range(Max + 1):        if freq[i] == 3:            print(i,end = " ") # Driver Codearr1 = [ 1, 5, 10, 20, 40, 80 ]arr2 = [ 6, 7, 20, 80, 100 ]arr3 = [ 3, 4, 15, 20, 30, 70, 80, 120 ] commonElements(arr1, arr2, arr3, 6, 5, 8) # This code is contributed by shinjanpatra
// C# implementation of the above approachusing System;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 = int.MinValue;         // 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)                Console.Write(i + " ");    }     // Driver Code    public static void 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 };         commonElements(arr1, arr2, arr3, 6, 5, 8);    }}
<script>// javascript implementation of the above approach   function commonElements(arr1,  arr2,  arr3 , n1 , n2 , 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        var max = Number.MIN_VALUE;         // deleting duplicates in linear time        // for arr1        var res1 = 1;        for (var 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        var res2 = 1;        for (var 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        var res3 = 1;        for (var 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        var freq = Array(max + 1).fill(0);         // calculating the frequency of        // all the elements present in        // all the array        for (i = 0; i < res1; i++)            freq[arr1[i]]++;        for (i = 0; i < res2; i++)            freq[arr2[i]]++;        for (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 (i = 0; i <= max; i++)            if (freq[i] == 3)                document.write(i + " ");    }     // Driver Code         var arr1 = [ 1, 5, 10, 20, 40, 80 ];        var arr2 = [ 6, 7, 20, 80, 100 ];        var arr3 = [ 3, 4, 15, 20, 30, 70, 80, 120 ];         commonElements(arr1, arr2, arr3, 6, 5, 8); // This code is contributed by Rajput-Ji</script>
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 arrays. 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++
Python3
Javascript
#include <bits/stdc++.h>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 < n1; i++) {        uset.insert(a[i]);    }    for (int i = 0; i < n2; i++) {        uset2.insert(b[i]);    }    // checking if elements of 3rd array are present in    // first 2 sets    for (int i = 0; i < n3; i++) {        if (uset.find(c[i]) != uset.end()            && uset2.find(c[i]) != uset.end()) {            // using a 3rd set to prevent duplicates            if (uset3.find(c[i]) == uset3.end())                cout << c[i] << " ";            uset3.insert(c[i]);        }    }} // Driver codeint 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 " << endl;    findCommon(ar1, ar2, ar3, n1, n2, n3);    return 0;}
# Python implementation of the approachdef findCommon(a, b, c, n1, n2, n3):     # three sets to maintain frequency of elements    uset = set()    uset2 = set()    uset3 = set()    for i in range(n1):        uset.add(a[i])     for i in range(n2):        uset2.add(b[i])     # checking if elements of 3rd array are present in first 2 sets    for i in range(n3):         if(c[i] in uset and c[i] in uset2):             # using a 3rd set to prevent duplicates            if c[i] not in uset3:                print(c[i], end = " ")            uset3.add(c[i]) # Driver codear1 = [ 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 shinjanpatra.
<script> function findCommon(a, b, c, n1, n2, n3){     // three sets to maintain frequency of elements    let uset = new Set();    let uset2 = new Set();    let uset3 = new Set();    for(let i=0;i<n1;i++){        uset.add(a[i]);    }     for(let i=0;i<n2;i++){        uset2.add(b[i]);    }      // checking if elements of 3rd array are present in first 2 sets    for(let i=0;i<n3;i++)    {        if(uset.has(c[i]) == true && uset2.has(c[i]) == true)        {            // using a 3rd set to prevent duplicates            if(uset3.has(c[i]) == false)                document.write(c[i]," ");            uset3.add(c[i]);        }    }          } // Driver codelet ar1 = [ 1, 5, 10, 20, 40, 80 ];let ar2 = [ 6, 7, 20, 80, 100 ];let ar3 = [ 3, 4, 15, 20, 30, 70, 80, 120 ];let n1 = ar1.length;let n2 = ar2.length;let n3 = ar3.length; document.write("Common Elements are ","</br>");findCommon(ar1, ar2, ar3, n1, n2, n3); // This code is contributed by shinjanpatra.</script>
Common Elements are 
20 80 
 Time Complexity: O(n1 + n2 + n3) Space complexity: O(n1 + n2 + n3) 
Method 5: Using Binary Search
This approach is a modification of previous approach. Here Instead of using map, we use binary search to find elements of 1st array that are present in 2nd and 3rd arrays.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>using namespace std; bool binary_search(int arr[], int n, int element){    int l = 0, h = n - 1;    while (l <= h) {        int mid = (l + h) / 2;        if (arr[mid] == element) {            return true;        }        else if (arr[mid] > element) {            h = mid - 1;        }        else {            l = mid + 1;        }    }    return false;}void findCommon(int a[], int b[], int c[], int n1, int n2,                int n3){    // Iterate on first array    for (int j = 0; j < n1; j++) {        if (j != 0 && a[j] == a[j - 1]) {            continue;        }        // check if the element is present in 2nd and 3rd        // array.        if (binary_search(b, n2, a[j])            && binary_search(c, n3, a[j])) {            cout << a[j] << " ";        }    }} // Driver codeint 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 " << endl;    findCommon(ar1, ar2, ar3, n1, n2, n3);    return 0;} // This code is contributed by Anchal Agarwal
Common Elements are 
20 80 
Time complexity: O(n1(log(n2*n3))
Space complexity: O(1)
This article is compiled by Rahul Gupta Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 
Sam007
vt_m
le0
akashsingh1302
rdtank
rrrtnx
anushikasethh
surindertarika1234
professor99
rajsanghavi9
samim2000
splevel62
gfgking
Rajput-Ji
simranarora5sos
shinjanpatra
agarwalanchal72
MAQ Software
Arrays
Searching
MAQ Software
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Introduction to Arrays
Linear Search
Binary Search
Linear Search
Maximum and minimum of an array using minimum number of comparisons
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1