Find First And Last Position of Element in Sorted Array

·

1 min read

Problem Statement:-

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

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

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8

Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6

Output: [-1,-1]

Example 3:

Input: nums = [], target = 0

Output: [-1,-1]

Approach:-

An efficient approach to this problem is to use Binary Search to search the first and the last index.

class Solution {
public:
    int first_index(vector<int>& nums, int target)
    {
        int start=0,end=nums.size()-1;
        int ans=-1;
        while(start<=end)
        {
            //Normal Binary Search Logic
            int mid=(start+end)/2;
            if(nums[mid]>target) end=mid-1;
            else if(nums[mid]<target) start=mid+1;
            else {
                    // If arr[mid] is same as target, we
                    // update ans and move to the left half
                ans=mid;
                end=mid-1;
            }
        }
        return ans;
    }
    int second_index(vector<int>& nums, int target)
    {
        int start=0,end=nums.size()-1;
        int ans=-1;
        while(start<=end)
        {
            //Normal Binary Search Logic
            int mid=(start+end)/2;
            if(nums[mid]>target) end=mid-1;
            else if(nums[mid]<target) start=mid+1;
                    // If arr[mid] is same as target, we
                    // update ans and move to the right half
            else {
                ans=mid;
                start=mid+1;
            }
        }
        return ans;
    }
    vector<int> searchRange(vector<int>& nums, int target) {
        vector<int> ans;
        ans.push_back(first_index(nums,target));
        ans.push_back(second_index(nums,target));
        return ans;
    }
};

Time Complexity: O(log n)

Auxiliary Space: O(1)