4. Find First and Last Position of Element in Sorted Array

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].

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

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]
class Solution
{
public:
    int firstOcc(vector<int> &arr, int start, int end, int target)
    {

        while (start <= end)
        {
            int mid = (start + end) / 2;
            if ((mid == 0 || arr[mid - 1] < arr[mid]) && arr[mid] == target)
            {
                return mid;
            }
            else if (target <= arr[mid] )
            {
                end = mid - 1;
            }
            else
            {
                start = mid + 1;
            }
        }
        return -1;
    }

    int lastOcc(vector<int> &arr, int start, int end, int target)
    {

        while (start <= end)
        {
            int mid = (start + end) / 2;
            if ((mid == arr.size() - 1 || arr[mid + 1] > arr[mid]) && arr[mid] == target)
            {
                return mid;
            }
            else if (target >= arr[mid])
            {
                start = mid + 1; 
            }
            else
            {
                end = mid - 1;
            }
        }
        return -1;
    }

    vector<int> searchRange(vector<int> &nums, int target)
    {
        vector<int> v;
        int start = firstOcc(nums, 0, nums.size() - 1, target);
        int end = lastOcc(nums, 0, nums.size() - 1, target);
        v.push_back(start);
        v.push_back(end);
        return v;
    }
};

Time Complexity: O(log n)

Last updated