problem:Given three Sorted arrays in non-decreasing order, print all common elements in these arrays.
solution suggests declaring 3 vars i,j and k for every array and to increment them only when the element is a minimum. But why not incrementing it anyways, as long as the element is not the maximum?!
correct solution
ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// Initialize three pointers for each array
int i = 0, j = 0, k = 0;
// Initialize an arraylist to store the common elements
ArrayList<Integer> res = new ArrayList<Integer>();
// Initialize a variable to store the last checked element
int last = Integer.MIN_VALUE;
// Loop until any of the three arrays reaches its end
while (i < n1 && j < n2 && k < n3)
{
// If the current elements of all three arrays are equal and not the same as the last checked element
if (A[i] == B[j] && A[i] == C[k] && A[i] != last)
{
// Add the common element to the result arraylist
res.add (A[i]);
// Update the last checked element
last = A[i];
// Move to the next element in each array
i++;
j++;
k++;
}
// If the current element of array A is the smallest, move to the next element in array A
else if (Math.min (A[i], Math.min(B[j], C[k])) == A[i]) i++;
// If the current element of array B is the smallest, move to the next element in array B
else if (Math.min (A[i], Math.min(B[j], C[k])) == B[j]) j++;
// If the current element of array C is the smallest, move to the next element in array C
else k++;
}
my solution
public static ArrayList<Integer> commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList <Integer> res=new ArrayList <Integer>();
int i=0;
int j=0;
int k=0;
long last=Long.MIN_VALUE;
while(i<n1 && j<n2 && k<n3){
if(A[i]==B[j] && B[j]==C[k] && A[i]!=last){
res.add(A[i]);
last=A[i];
i++;
j++;
k++;
}else if(A[i]!=Math.max(A[i],Math.max(B[j],C[k]))){
i++;
}else if(B[j]!=Math.max(A[i],Math.max(B[j],C[k]))){
j++;
}else if( C[k]!=Math.max(A[i],Math.max(B[j],C[k]))){
k++;
}
}
return res;
}