I'm solving the following programming question:
Given a sorted integer array and a number, find the start and end indexes of the number in the array.
Ex1: Array = {0,0,2,3,3,3,3,4,7,7,9} and Number = 3 --> Output = {3,6}
Ex2: Array = {0,0,2,3,3,3,3,4,7,7,9} and Number = 5 --> Output = {-1,-1}
Complexity should be less than O(n)
My Solution is as follows:
public static void findStartEndIndex(int[] arr, int elem) {
int elemIndex = binarySearch(arr, elem, 0, arr.length);
if(elemIndex == -1)
System.out.println("-1,-1");
int lowIndex = elemIndex - 1;
int highIndex = elemIndex + 1;
//Find the first index in the lower half of the array
while(lowIndex >= 0 && (elemIndex = binarySearch(arr, elem, 0, lowIndex)) != -1)
lowIndex = elemIndex -1;
//Find the last index in the upper half of the array
while(highIndex < arr.length && (elemIndex = binarySearch(arr, elem, highIndex, arr.length - 1)) != -1)
highIndex = elemIndex + 1;
System.out.println((lowIndex + 1) + ", " + (highIndex -1));
}
I'm having difficulty trying to find the time complexity of the above program. Following is my approach:
From my understanding, the worst case will be when all the elements are same: {3,3,3,3,3,3}
Finding the first occurence will cost me: O(logn) //Binary Search
For each half of the array(upper and lower), I'm calling binarySearch at most O(logn)
times.
So, the total complexity will be O(logn ^2)
Is this the correct analysis? And, is O(logn^2)
better than O(n)
?