Find common elements in three sorted arrays

• Difficulty Level : Easy
• Last Updated : 27 Jul, 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

Recommended Practice

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 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;} // 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 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]) {            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 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]);     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 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

 # 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#

 // 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

 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.

Auxiliary Space:   O(1)

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 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++];        }         // If x < y, update prev1 and increment i        else if (ar1[i] < ar2[j])            prev1 = ar1[i++];         // If y < z, update prev2 and increment j        else if (ar2[j] < ar3[k])            prev2 = ar2[j++];         // We reach here when x > y and z < y, i.e., z is        // smallest update prev3 and increment k        else            prev3 = ar3[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;} // This code is contributed by Aditya Kumar (adityakumar129)

C

 // C program to print common elements in three arrays#include #include  // 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]) {            printf("%d ", ar1[i]);            prev1 = ar1[i++];            prev2 = ar2[j++];            prev3 = ar3[k++];        }         // If x < y, update prev1 and increment i        else if (ar1[i] < ar2[j])            prev1 = ar1[i++];         // If y < z, update prev2 and increment j        else if (ar2[j] < ar3[k])            prev2 = ar2[j++];         // We reach here when x > y and z < y, i.e., z is        // smallest update prev3 and increment k        else            prev3 = ar3[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]);     printf("Common Elements are ");    findCommon(ar1, ar2, ar3, n1, n2, n3);    return 0;} // This code is contributed by Aditya Kumar (adityakumar129)

Java

 // 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 increment 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.

Python3

 # 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 increment 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#

 // 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 increment 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.

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.

C++

 // C++ program for the above approach #include using namespace std; void commonElements(vectorarr1,vectorarr2,vectorarr3 ,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_MIN;     // deleting duplicates in linear time    // for arr1    int res1 = 1;    for (int i = 1; i < n1; i++) {        Max = 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 = 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 = max(arr3[i], Max);        if (arr3[i] != arr3[res3 - 1]) {            arr3[res3] = arr3[i];            res3++;        }    }     // creating an array for finding frequency    vectorfreq(Max + 1,0);     // 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){            cout<arr1 = { 1, 5, 10, 20, 40, 80 };vectorarr2 = { 6, 7, 20, 80, 100 };vectorarr3 = { 3, 4, 15, 20, 30, 70, 80, 120 }; commonElements(arr1, arr2, arr3, 6, 5, 8); } // This code is contributed by shinjanpatra

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);    }}

Python3

 # 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#

 // 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);    }}

Javascript



Output

20 80

Time Complexity: O(n1 + n2)
Auxiliary Space: O(maximum element in array))

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++

 #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 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;}

Java

 /*package whatever //do not write package name here */ import java.io.*; class GFG {    static void findCommon(int a[], int b[], int c[], int n1, int n2,int n3){    // three sets to maintain frequency of elements    HashSet uset = new HashSet<>();    HashSet uset2 = new HashSet<>();    HashSet uset3 = new HashSet<>();    for (int i = 0; i < n1; i++) {        uset.add(a[i]);    }    for (int i = 0; i < n2; i++) {        uset2.add(b[i]);    }    // checking if elements of 3rd array are present in    // first 2 sets    for (int i = 0; i < n3; i++) {        if (uset.contains(c[i]) && uset2.contains(c[i])) {            // using a 3rd set to prevent duplicates            if (uset3.contains(c[i]) == false)                System.out.print(c[i]+" ");            uset3.add(c[i]);        }    }} // Driver Codepublic static void main(String args[]){    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 = ar1.length;    int n2 = ar2.length;    int n3 = ar3.length;     System.out.println("Common Elements are ");    findCommon(ar1, ar2, ar3, n1, n2, n3);}} // This code is contributed by shinjanpatra

Python3

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



C#

 using System;using System.Collections.Generic; public class GFG {    static void findCommon(int[] a, int[] b, int[] c,                           int n1, int n2, int n3)    {        // three sets to maintain frequency of elements        HashSet uset = new HashSet();        HashSet uset2 = new HashSet();        HashSet uset3 = new HashSet();        for (int i = 0; i < n1; i++) {            uset.Add(a[i]);        }        for (int i = 0; i < n2; i++) {            uset2.Add(b[i]);        }        // checking if elements of 3rd array are present in        // first 2 sets        for (int i = 0; i < n3; i++) {            if (uset.Contains(c[i])                && uset2.Contains(c[i])) {                // using a 3rd set to prevent duplicates                if (!uset3.Contains(c[i])) {                    Console.Write(c[i]);                    Console.Write(" ");                }                uset3.Add(c[i]);            }        }    }     // Driver code    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 };         int n1 = ar1.Length;        int n2 = ar2.Length;        int n3 = ar3.Length;         Console.Write("Common Elements are ");        Console.Write("\n");        findCommon(ar1, ar2, ar3, n1, n2, n3);    }}// This code is contributed by Aarti_Rathi

Output

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 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

Java

 // Java program to implement// above approachpublic class Main{     public static boolean 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; }         public static 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])) {                                 System.out.print(a[j] + " ");                             }        }    }     /* Driver code */public static void main(String[] args)    {         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 = ar1.length;        int n2 = ar2.length;        int n3 = ar3.length;         System.out.println("Common elements are ");        // function calling        findCommon(ar1, ar2, ar3, n1, n2, n3);    }} //this code is contributed by Machhaliya Muhammad

Python3

 # Python program to Find all range# Having set bit sum X in array  def binary_search(arr, n, element):     l,h = 0,n - 1    while (l <= h):        mid = (l + h) // 2        if (arr[mid] == element):            return True         elif (arr[mid] > element):            h = mid - 1         else:            l = mid + 1     return False def findCommon(a, b, c, n1, n2, n3):     # Iterate on first array    for j in range(n1):        if (j != 0 and a[j] == a[j - 1]):            continue             # check if the element is present in 2nd and 3rd        # array.        if (binary_search(b, n2, a[j]) and binary_search(c, n3, a[j])):            print(a[j],end=" ")  # Driver code 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 shinjanpatra



C#

 // C# program to implement// above approach using System; public class GFG{     public static 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;    }     public static 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]))            {                 Console.Write(a[j] + " ");             }        }    }     /* Driver code */    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 };        int n1 = ar1.Length;        int n2 = ar2.Length;        int n3 = ar3.Length;        Console.WriteLine("Common elements are ");        // function calling        findCommon(ar1, ar2, ar3, n1, n2, n3);    }} //this code is contributed by Saurabh Jaiswal

Output

Common Elements are
20 80

Time complexity: O(n1(log(n2*n3))

Space complexity: O(1)