Please look into my code and tell me whats the error.
Find Upper and Lower Bound
#include #include using namespace std; int upperBound(int *a, int n, int key){ int left = 0; int right = n - 1; int ans = -1; while(left <= right){ int mid = (left + right)/2; if(a[mid] == key){ ans = key; left = mid + 1; }else if(a[mid] > key){ right = mid - 1; }else{ left = mid + 1; } } return ans; } int lowerBound(int *a, int n, int key){ int left =0; int right = n - 1; int ans = -1; while(left<= right){ int mid = (left + right)/2; if(a[mid] == key){ ans = mid; right = mid - 1; }else if(a[mid] < key){ left = mid + 1; }else{ right = mid - 1; } } return ans; } int main() { int n; cin>>n; int arr[100000]; for(int i=0; i<n; i++){ cin>>arr[i]; } int times; cin>>times; while(times–){ int t; cin>>t; cout<<lowerBound(arr, n, t)<<" "<<upperBound(arr, n, t)<<endl; } return 0; }
for input
4
1 1 1 1
2
1
2
Your Code’s Output
0 -1
-1 -1
Correct Output
0 3
-1 -1
your Condition is not correct
Simple And Correct condition will be like this
int val;
cin>>val;
int lb=lower_bound(a,a+n,val)-a;
if(val > a[n-1] || a[lb]>val){
//element not found
cout<<"-1 -1"<<endl;
}else{
// element found in the array
// now find upper bound
int ub = upper_bound(a,a+n,val)-a -1 ;
cout<<lb<<" "<<ub<<endl;
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.