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.

Return an array [first, last] where:

  • first is the index of the first occurrence of target in nums.
  • last is the index of the last occurrence of target in nums.

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

Your algorithm must run in O(log n) time.

Example 1
Inputnums = [5,7,7,8,8,10], target = 8
Output[3,4]
The target value 8 appears first at index 3 and last at index 4.
Example 2
Inputnums = [5,7,7,8,8,10], target = 6
Output[-1,-1]
The target value 6 does not appear in the array, so both positions are -1.

Constraints

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

Asked at 31 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate