Basic Approach: Binary Search
Steps:
1> first we find lowerBound
2> Second we find UpperBound
when we call both method in main function we check our lowerbound is equal to array length or not present in array if true then return {-1,-1}
otherwise return {lowerbound,upperbound-1}
Time Complexity : O(log n)
Space Complexity : O(1)
public static int[] searchRange(int []arr, int x) {
int lowerbound=LowerBound(arr, x);
if(lowerbound==arr.length ||arr[lowerbound]!=x)return new int[]{-1,-1};
else return new int[]{lowerbound,UpperBound(arr, x)-1};
}
public static int LowerBound(int arr[],int x){
int start=0,end=arr.length-1, ans=arr.length;
while(start<=end){
int mid=(start+end)/2;
if(arr[mid]>=x){
ans=mid;
end=mid-1;
}
else start=mid+1;
}
return ans;
}
public static int UpperBound(int arr[],int x){
int start=0,end=arr.length-1,ans=arr.length;
while(start<=end){
int mid=(start+end)/2;
if(arr[mid]>x){
ans=mid;
end=mid-1;
}
else start=mid+1;
}
return ans;
}