Simple C++ Solution Using Binary Search, Lower & Upper Bound

vector Solution::searchRange(const vector &A, int B) {

int i,j,k,l=0,x=-1,y=-1,z=0;
vector<int> vv;
k = A.size();
int low,mid,high;
low = 0;
high = (k-1);
if(A[low]==B && A[high]==B)
{
    vv.push_back(low);
    vv.push_back(high);
    return vv;
}

low = 0;
high = k-1;

while(low<=high)
{
    mid = (low+high)/2;
    if(A[mid]==B)
    {
       x = low;
       y = high;
       z = mid;
       break;
    }
    
    if(A[mid]>B)
    high = mid-1;
    else
    low = mid + 1;
}

if(x==-1 && y==-1)
{
    vv.push_back(-1);
    vv.push_back(-1);
    return vv;
}

j = A[z];

if(A[x]==B && A[y]==B)
{
    vv.push_back(x);
    vv.push_back(y);
    return vv;
}

low = x;
for(i=low;i<=z;i++)
{
    if(A[i]==j)
    {
        x=i;
        break;
    }
}

high  = y;
 for(i=high;i>=z;i--)
{
    if(A[i]==j)
    {
        y=i;
        break;
    }
}

 vv.push_back(x);
    vv.push_back(y);
    return vv;

}

Click here to start solving coding interview questions