# Easy to implement C++ Solution : 2 Binary Searches for B in A. Open for suggestions

``````int searchForFirst(const vector<int> &A, int B) {
int lo = 0, hi = A.size()-1;
int first=INT_MAX;
while(lo<=hi) {
int mid = lo + (hi-lo)/2;
if(A[mid]==B) {
if(first > mid)
first = mid;
hi = mid-1;
}
else if(A[mid] < B)
lo = mid+1;
else if(A[mid] > B)
hi = mid-1;
}
if(first != INT_MAX)
return first;
else
return -1;
}

int searchForLast(const vector<int> &A, int B) {
int lo = 0, hi = A.size()-1;
int last=INT_MIN;
while(lo<=hi) {
int mid = lo + (hi-lo)/2;
if(A[mid]==B) {
if(last < mid)
last = mid;
lo = mid+1;
}
else if(A[mid] < B)
lo = mid+1;
else if(A[mid] > B)
hi = mid-1;
}
if(last!=INT_MIN)
return last;
else
return -1;
}

vector<int> Solution::searchRange(const vector<int> &A, int B) {
if(A.size() == 0)
return {-1, -1};
int left = searchForFirst(A,B);
int right = searchForLast(A,B);
return {left, right};
}``````
``````int find_first(const vector<int> &A, int s, int e, int B)
{
if(s<=e)
{
int m = (s+e)/2;
if(A[m] == B && (A[m-1] < B || m==0))
return m;
else if(B <= A[m-1])
return find_first(A, s, m-1, B);
else
return find_first(A, m+1, e, B);
}
return -1;
}
int find_last(const vector<int> &A, int s, int e, int B)
{
if(s<=e)
{
int m = (s+e)/2;
if(A[m] == B && (B < A[m+1] || m==A.size()-1))
return m;
else if(B < A[m])
return find_last(A, s, m-1, B);
else
return find_last(A, m+1, e, B);
}
return -1;
}

vector<int> Solution::searchRange(const vector<int> &A, int B)
{
vector<int> res(2);
res[0] = find_first(A, 0, A.size()-1, B);
res[1] = find_last(A, 0, A.size()-1, B);
return res;
}``````