After I moved from C++ to java, I have trouble writing correct code for matching std::upper_bound
and std::lower_bound
logic from C++ Vector.
So it causes problems in interviews if lower bound is being used in the coding questions.
Example
upper_bound gives the the max index of element in array.
Suppose Arr[]= {1,2,3,4,4}
:
Upper bound for 4 -> 5 index
Similarly lower bound for 4 -> 4 index
For cases where element not found:
Similarly upper bound for element 6 in the above array will be index 5
Lower bound for element 0 in above array will be index 0
I just wanted to ask how to come up with the upper bound and lower bound code without hit and trial method. I just need a good explanation.
Upper bound:
It returns an iterator pointing to the first element in the range [first, last) that is greater than value, or last if no such element is found. The elements in the range shall already be sorted or at least partitioned with respect to val.
Lower Bound
The lower_bound() method in C++ is used to return an iterator pointing to the first element in the range [first, last) which has a value not less than val. This means that the function returns the index of the next smallest number just greater than or equal to that number. If there are multiple values that are equal to val, lower_bound() returns the index of the first such value.
My code:
static int lowerbound(int size, int arr[],int element){
if(arr[size -1]<=element)
return size-1;
if(element<arr[0])
return 0;
int low=0;
int high=size-1;
while(low<high){
int mid=(low+high)/2;
if(arr[mid]<element) {
low = mid+1;
}else{
high=mid;
}
// System.out.println(low+" "+mid+ " "+high);
}
return low;
}
public static void main (String[] args) {
int arr[]={1,2,6,10,10,13};
System.out.println(lowerbound(6,arr,14));//5
System.out.println(lowerbound(6,arr,11));//5
System.out.println(lowerbound(6,arr,10));//3
System.out.println(lowerbound(6,arr,3));//2
int arr2[]={1,2,6,10,10,10,13};
System.out.println(lowerbound(7,arr2,14));//6
System.out.println(lowerbound(7,arr2,11));//6
System.out.println(lowerbound(7,arr2,10));//3
System.out.println(lowerbound(7,arr2,3));//2
}
It took me too much time and debugging to arrive at the correct algorithm. Can anybody explain how to remember or figure out the logic easily?