Find common elements in three sorted arrays - GeeksforGeeks
Given three arrays sorted in non-decreasing order, print all common elements in these 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.
1) If x, y and z are same, we can simply print any of them as common element and move ahead in all three arrays.
2) Else If x < y, we can move ahead in ar1[] as x cannot be a common element
3) Else If y < z, we can move ahead in ar2[] as y cannot be a common element
4) Else (We reach here when x > y and y > z), we can simply move ahead in ar3[] as z cannot be a common element.
Read full article from Find common elements in three sorted arrays - GeeksforGeeks
Given three arrays sorted in non-decreasing order, print all common elements in these 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.
1) If x, y and z are same, we can simply print any of them as common element and move ahead in all three arrays.
2) Else If x < y, we can move ahead in ar1[] as x cannot be a common element
3) Else If y < z, we can move ahead in ar2[] as y cannot be a common element
4) Else (We reach here when x > y and y > z), we can simply move ahead in ar3[] as z cannot be a common element.
int
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++;
}
}