Find common elements in three sorted arrays in C++

C++Server Side ProgrammingProgramming

Suppose we have three arrays with some elements. We have to find all the common elements that are present in these three arrays. Suppose these elements are [10, 12, 15, 20, 25], [10, 12, 13, 15] and [10, 12, 15, 24, 25, 26], then the common elements in these three arrays are 10, 12 and 15.

Suppose current element traversed in array A1 be x, A2 be y and A3 be z. We can have the following cases for them −

  • If x, y, and z are same, then we will print any of them, and increase each array elements by 1

  • When x < y, then we will move ahead in A1 as x cannot be a common element

  • When x > z and y > z, then we will move ahead for A3, as z cannot be a common element.

Example

 Live Demo

#include<iostream>
using namespace std;
void findCommonValues(int A1[], int A2[], int A3[], int n1, int n2, int n3) {
   int i = 0, j = 0, k = 0;
   while (i < n1 && j < n2 && k < n3) {
      if (A1[i] == A2[j] && A2[j] == A3[k]) {
         cout << A1[i] << " "; i++; j++; k++;
      }
      else if (A1[i] < A2[j])
         i++;
      else if (A2[j] < A3[k])
         j++;
      else
         k++;
   }
}
int main() {
   int A1[] = {10, 12, 15, 20, 25};
   int n1 = sizeof(A1)/sizeof(A1[0]);
   int A2[] = {10, 12, 13, 15};
   int n2 = sizeof(A2)/sizeof(A2[0]);
   int A3[] = {10, 12, 15, 24, 25, 26};
   int n3 = sizeof(A3)/sizeof(A3[0]);
   cout << "Common elements are: ";
   findCommonValues(A1, A2, A3, n1, n2, n3);
}

Output

Common elements are: 10 12 15
raja
Published on 19-Dec-2019 07:25:08
Advertisements