Intersection of Three Sorted Arrays in C++


Suppose there are three integer arrays arr1, arr2 and arr3 and they are sorted in strictly increasing order, we have to return a sorted array of only the integers that appeared in all of these three arrays. So if arrays are [1,2,3,4,5], [1,2,5,7,9], and [1,3,4,5,8], so the output will be [1,5]

To solve this, we will follow these steps −

  • define an array called res
  • create three maps f1, f2 and f3
  • for i in range 0 to length of arr1
    • f1[arr1[i]] increase by 1
  • for i in range 0 to length of arr2
    • f2[arr2[i]] increase by 1
  • for i in range 0 to length of arr3
    • f3[arr3[i]] increase by 1
  • for i = 1 to 2000,
    • if f1[i] and f2[i] and f3[i], then
      • insert i into the res array
  • return res

Example

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << v[i] << ", ";
   }
   cout << "]"<<endl;
}
class Solution {
public:
   vector<int> arraysIntersection(vector<int>& arr1, vector<int>& arr2, vector<int>& arr3) {
      vector <int> ans;
      unordered_map <int,int> f1,f2,f3;
      for(int i =0;i<arr1.size();i++){
         f1[arr1[i]]++;
      }
      for(int i =0;i<arr2.size();i++){
         f2[arr2[i]]++;
      }
      for(int i =0;i<arr3.size();i++){
         f3[arr3[i]]++;
      }
      for(int i =1;i<=2000;i++){
         if(f1[i] && f2[i] && f3[i])ans.push_back(i);
      }
      return ans;
   }
};
main(){
   Solution ob;
   vector<int> v1 = {1,2,3,4,5};
   vector<int> v2 = {1,2,5,7,9};
   vector<int> v3 = {1,3,4,5,8};
   print_vector(ob.arraysIntersection(v1, v2, v3));
}

Input

[1,2,3,4,5]
[1,2,5,7,9]
[1,3,4,5,8]

Output

[1,5]

Updated on: 28-Apr-2020

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements