Better
int searchInsert(vector<int>& arr, int x)
{
int n=arr.size();
int low=0;
int high=n-1;
int ans=n;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]>=x){
ans=mid;
high=mid-1;
}
else{
low=mid+1;
}
}
return ans;
}
Optimal
#include<bits/stdc++.h>
int lb(vector<int>& arr,int n,int k){
int low=0;
int high=n-1;
int first=-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]==k) {
first=mid;
high=mid-1;
}
else if(arr[mid]<k){
low=mid+1;
}
else{
high=mid-1;
}
}
return first;
}
int ub(vector<int>& arr,int n,int k){
int low=0;
int high=n-1;
int last=-1;
while(low<=high){
int mid=(low+high)/2;
if(arr[mid]==k){
last=mid;
low=mid+1;
}
else if(arr[mid]<k){
low=mid+1;
}
else{
high=mid-1;
}
}
return last;
}
pair<int, int> firstAndLastPosition(vector<int>& arr, int n, int k){
if(lb(arr,n,k)==-1){
return {-1,-1};
}
return {lb(arr,n,k) , ub(arr,n,k)};
}