This was the question, I was asked in interview.
What is the best time complexity you can get to find a min and max of array?
I replied: O(n). Iterate through the array, keeping track of the max and min found so far. very simple and straightForward.
The interviewer asked can you improve it using divide and conquer. I said probably not. Then the conversation went on and finally I was asked to implement divide and conquer approach.
Here it is:
public class MinMaxInArray {
public static int[] findMinMax(int[] array, int i, int j){
// base cases
int arrLen = j - i + 1;
if (arrLen == 1)
return new int[]{array[i], array[j]}; //j and i are the same
if (arrLen == 2){
int min = Math.min(array[i], array[j]);
int max = Math.max(array[i], array[j])
return new int[]{min, max};
}
// actual divide and conquer
int mid = i + (j-i)/2;
int[] leftMinMax = findMinMax(array, i, mid);
int[] rightMinMax = findMinMax(array, mid+1, j);
return new int[]{ Math.min(leftMinMax[0], rightMinMax[0]), Math.max(leftMinMax[1], rightMinMax[1]) };
}
public static void main(String[] args){
int[] array = {20, 5, 7, 25, 30, 1, 9, 12};
int[] minMax= findMinMax(array, 0, array.length - 1); //minMax[0] = minimum value, minMax[1] = maximum value
System.out.println("min = " + minMax[0] + ", max = " + minMax[1] );
}
}
I am confident that this is still O(n) since all elements are compared. But the interviewer insisted that it is O(log n) and asked me to think about it. I thought quite a bit and I am convinced it is O(n). Just applying divide and conquer does not always reduce complexity if I am correct.
Please correct me if my understanding that this algorithm is still O(n).
Thank you