Better
#include<bits/stdc++.h>
int findFloor(vector<int> &arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
// maybe an answer
if (arr[mid] <= x) {
ans = arr[mid];
//look for smaller index on the left
low = mid + 1;
}
else {
high = mid - 1; // look on the right
}
}
return ans;
}
int findCeil(vector<int> &arr, int n, int x) {
int low = 0, high = n - 1;
int ans = -1;
while (low <= high) {
int mid = (low + high) / 2;
// maybe an answer
if (arr[mid] >= x) {
ans = arr[mid];
//look for smaller index on the left
high = mid - 1;
}
else {
low = mid + 1; // look on the right
}
}
return ans;
}
pair<int, int> getFloorAndCeil(vector<int> &arr, int n, int x) {
int f = findFloor(arr, n, x);
int c = findCeil(arr, n, x);
return {f, c};
}
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)};
}