A special site for solving fun programming problems and challenges, interested in computer science, programming, basics, data structure and algorithms

 


Given three arrays sorted in increasing order. Find the elements that are common in all three arrays.

Note: can you take care of the duplicates without using any additional Data Structure?

Example 1:

Input:
n1 = 6; A = {1, 5, 10, 20, 40, 80}
n2 = 5; B = {6, 7, 20, 80, 100}
n3 = 8; C = {3, 4, 15, 20, 30, 70, 80, 120}
Output: 20 80
Explanation: 20 and 80 are the only
common elements in A, B and C.

 

Your Task:  
You don't need to read input or print anything. Your task is to complete the function commonElements() which take the 3 arrays A[], B[], C[] and their respective sizes n1, n2 and n3 as inputs and returns an array containing the common element present in all the 3 arrays in sorted order. 
If there are no such elements return an empty array. In this case the output will be printed as -1.

 


Expected Time Complexity: O(n1 + n2 + n3)
Expected Auxiliary Space: O(n1 + n2 + n3)

 

Constraints:
1 <= n1, n2, n3 <= 10^5
The array elements can be both positive or negative integers.


  1. class Solution
  2. {
  3.     public:    
  4.        vector <int> commonElements (int A[], int B[], int C[], int n1, int n2, int n3)
  5.         {
  6.             //code here.
  7.             vector<int> v;
  8.             int i=0,j=0,k=0;
  9.             while(i<n1 && j<n2 && k<n3)
  10.             {
  11.                 if(A[i]==B[j]&&A[i]==C[k])
  12.                 {
  13.                     v.push_back(A[i]);
  14.                     i++;
  15.                     j++;
  16.                     k++;
  17.                 }else if(A[i]<B[j])
  18.                 {
  19.                     i++;
  20.                 }else if(B[j]<C[k])
  21.                 {
  22.                     j++;
  23.                 }else 
  24.                 {
  25.                     k++;
  26.                 }
  27.             }
  28.             sort(v.begin(),v.end());
  29.             v.erase(unique(v.begin(),v.end()),v.end());
  30.             return v;
  31.         }

  32. };

No comments:

Post a Comment