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.

Your algorithm’s runtime complexity must be in the order of O(log n).

If the 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]

Constraints:

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is a non decreasing array.
  • -10^9 <= target <= 10^9

Solution

C# Program

public class Solution {
    public int[] SearchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = findFirst(nums,target);
        result[1] = findLast(nums,target);
        return result;
    }
    
    public int findFirst(int[] nums,int target)
    {
        int index = -1;
        int start = 0, end = nums.Length-1;
        
        while(start <= end)
        {
            int mid = start + (end - start)/2;
            if(nums[mid] >= target )
            {
                end = mid - 1;
            }
            else
                start = mid + 1;
            
            if(nums[mid] == target)
                index = mid;
        }
        return index;
    }
    
    public int findLast(int[] nums,int target)
    {
        int index = -1;
        int start = 0, end = nums.Length-1;
        
        while(start <= end)
        {
            int mid = start + (end - start)/2;
            if(nums[mid] <= target)
            {
                start = mid+1;
            }
            else
                end = mid - 1;
            if(nums[mid] == target)
                index = mid;
        }
        return index;
    }
    
}

Time Complexity: O(log(n))

Space Complexity: O(1)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s