Find Upper and Lower Bound

My test case 0 is not passing though code is perfectly fine

#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll firstOccurance(ll arr[],ll n,ll m){
ll s=0,e=n;
ll ans=-1;
while(s<=e){
ll mid=(s+e)/2;
if(arr[mid]==m){
ans=mid;
e=mid-1;
}
else if(arr[mid]>=m)
e=mid-1;
else
s=mid+1;
}
return ans;
}
ll lastOccurance(ll arr[],ll n,ll m){
ll s=0,e=n;
ll ans=-1;
while(s<=e){
ll mid=(s+e)/2;
if(arr[mid]==m){
ans=mid;
s=mid+1;
}
else if(arr[mid]>=m)
e=mid-1;
else
s=mid+1;
}
return ans;
}
int main(){
ll n,m;
cin>>n;
ll arr[n];
for(ll i=0;i<n;i++)
cin>>arr[i];
int q;
cin>>q;
while(q–){
cin>>m;
cout<<firstOccurance(arr,n,m)<<" "<<lastOccurance(arr,n,m)<<endl;
}
return 0;
}

for binary search end value should be last index of the array which is n-1 in this case so take int e = n-1; in both of your function.

1 Like

Thanks alot it worked…!!!

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.

1 Like