Friday, 10 November 2017

C++ Program to find the Common Elements in Three Arrays

C++ Program to find out the common elements in the given three arrays is given below. Approach is simple we hashed the occurrence of the elements of first two arrays and then we will match if the element of array 3 is present in array 1 and array 2 or not.

Example:

ar1[] = {1, 5, 10, 20, 40, 80}
ar2[] = {6, 7, 20, 80, 100}
ar3[] = {3, 4, 15, 20, 30, 70, 80, 120}
The common elements in the above three arrays are: 20 80


PROGRAM:

#include <bits/stdc++.h>
using namespace std;
int main()
{
     int t;
     cout<<"\nEnter the number of test cases: \n";
     cin>>t;
     while(t--){
          int n1,n2,n3;
          
          int num;
          std::unordered_map<int,int> m1;
          std::unordered_map<int,int> m2;
        

          cout<<"\nEnter the number of elements in arr1: \n";
          cin>>n1;
          cout<<"\nEnter the elements of arr1: \n";
          for(int i=0;i<n1;i++) {
                 cin>>num;
                 m1[num]++;
          }

          cout<<"\nEnter the number of elements in arr2: \n";
          cin>>n2;
          cout<<"\nEnter the elements of arr2: \n";
          for(int i=0;i<n2;i++){
                 cin>>num;
                 m2[num]++;
          }

         
          std::vector<int> vect;


          cout<<"\nEnter the number of elements in arr3: \n";
          cin>>n3;
          cout<<"\nEnter the elements of arr3: \n";
          for(int i=0;i<n3;i++){
                 cin>>num;
                 if(m1[num]>0 && m2[num]>0){
                      vect.push_back(num);
                 }
          }
          
          cout<<"\n\nThe common elements are:\n";
          for(int i=0;i<vect.size();i++){
                cout<<vect[i]<<" ";
          }
          
          cout<<"\n";
     }
     return 0;
}


OUTPUT:




EmoticonEmoticon