I would like to know whether to Math.min and Math.max in java have the same time complexity because my problem was rejected for it took too long to be executed.
I worked on a problem which required adding common elemnts in 3 increasing sorted arrays.
The correct and optimized solution suggests that when one of A[i],B[j] or C[k] is the minimum of the three, the index of the array containing this min should increase by one.
My approach was that we should not only increase when the elemnt is min. But every index of the array of the element which is not the max should be increased
here is the optimized solution:`
ArrayList 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++;
}`
here is my solution:`
public static ArrayList commonElements(int A[], int B[], int C[], int n1, int n2, int n3)
{
// code here
ArrayList res=new ArrayList ();
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;
}
`