First and Last position of an element in sorted array | Binary Search Practice Example | Code Studio Interview Question

 Here I am writting only function solution not main part...

||It is based on Binary Search Example

Problem is there is given an array and you have to find a particular key of first and last index of that arry.

Example:-

Input format

2     // number of test Cases

6  3        // size of array      &&   the key element which have to find there first and last index in array

0  5  5  6  6  6

8  2

0  0  1  1  2  2  2  2  


Output

-1   -1     ///output is -1 because 3 is not present in the array

4    7    /// output is 4(first occurance) and 7 ( the last Occurance)


***************************************CODE**************************************

int firstocc(vector<int>& arr, int n, int key){

    int s=0;

    int e=n-1;

    int mid = s+(e-s)/2;

    int ans =-1;

    while(s<=e){

        if(arr[mid] == key){

            ans = mid;

            e = mid -1;            

        }

        else if(key> arr[mid]){   //right me jana hai

            s = mid +1;

        }

        else if(key < arr[mid]){   //left me jana hai

            e = mid -1;

        }

        mid = s + (e-s)/2;

    }

    return ans;

}

int lastocc(vector<int>& arr, int n, int key){

    int s=0;

    int e=n-1, ans =-1;

    int mid = s+(e-s)/2;

    while(s<=e){

        if(arr[mid] == key){

            ans = mid;

            s = mid +1;            

        }

        else if(key> arr[mid]){   //right me jana hai

            s = mid +1;

        }

        else if(key < arr[mid]){   //left me jana hai

            e = mid -1;

        }

        mid = s + (e-s)/2;

    }

    return ans;

}

pair<int, int> firstAndLastPosition(vector<int>& arr, int n, int k)

{

   pair<int, int> p;

    p.first = firstocc(arr, n, k);

    p.second = lastocc(arr, n, k);

    

    return p;

}



















Comments

Popular posts from this blog

Allocate Book Problem Solution || Code Studio

Peak Index in a Mountain Array || Binary Search practice example || Leet Code poblem #852