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.

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]

Constraints:

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

Solution

We want to find two positions, first_pos and last_pos of the target in nums.

For the first_pos, we want to find the leftmost target. So we will do binary search on nums, and whenever we find target, we search for its left side to see whether there is another target on the left while keeping track of the leftmost seen first_pos.

Similarly, we want to find the rightmost target in nums to be last_pos. So when we see a target, we search for its right side and record the last_pos = current index. If the current element is not target, then ordinary binary search will lead us to the correct searching side.

def searchRange(self, nums, target):
    left, right = 0, len(nums)-1
    first_pos, last_pos = -1, -1
    
    # find first pos
    while left <= right:
      mid = (left + right) // 2
      if nums[mid] == target:
          first_pos = mid
          right = mid - 1
      elif nums[mid] > target:
          right = mid - 1
      else:
          left = mid + 1
    
    #find last pos
    left, right = 0, len(nums)-1
    while left <= right:
      mid = (left + right) // 2
      if nums[mid] == target:
          last_pos = mid
          left = mid+1
      elif nums[mid] > target:
          right = mid - 1
      else:
          left = mid + 1
    return (first_pos, last_pos)

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator
Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

Which data structure is used to implement priority queue?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!