Find Starting and Ending Position of an element using BS: logN + logN

// https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/

Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1-1].

You must write an algorithm with O(log n) runtime complexity.

#include <bits/stdc++.h>
using namespace std;

int main(){

    int arr[] = {2,1,4,5,5,7,8,9,7,7,7,1};
    int x = 7;
    int target = x;

    vector<int> ans;
    // we will implement BS for start and end values simultaneously.

    int start = -1;
    int end = -1;



    //for start:
    int l = 0;
    int h = arr.size()-1;

    while(l <= h){
        int m = l + (s-l)/2;

        if(arr[m] < x) l = m+1;
        else if(arr[m] > x) h = m-1;
        else{
            // if i m on my x, there may be a chance that another x lie before it:
            //so will compress my range, but for now store it as well:
            start = m;
            h = m-1;
        }

    }
    ans.push_back(start);



    //for end:
    int l = 0;
    int h = arr.size()-1;

    while(l <= h){
        int m = l + (s-l)/2;

        if(arr[m] < x) l = m+1;
        else if(arr[m] > x) h = m-1;
        else{
            // if i m on my x, there may be a chance that another x lie before it:
            //so will compress my range, but for now store it as well:
            end = m;
            h = m-1;
        }

    }
    ans.push_back(end);


    //ans:
    cout << ans[0<< ans[1<< endl;

    return 0;
}

Comments

Popular Posts