Find First and Last Position of Element in Sorted Array

Medium Binary Search AI round

nums is a list of whole numbers in order from smallest to largest, where a number may appear more than once. target is a whole number.

Find the first and the last position of target in nums, counting from 0.

Return them as a list of two numbers, [first, last], or [-1, -1] if target is not in nums.

Example 1

Input: nums = [-4,0,3,3,3,8,12], target = 3
Output: [2,4]

3 is at positions 2, 3 and 4. The first of them is 2 and the last is 4.

Example 2

Input: nums = [1,5,5,9,9,9,14], target = 9
Output: [3,5]

Example 3

Input: nums = [2,6,10,15], target = 11
Output: [-1,-1]

Constraints

  • 0 ≤ nums.length ≤ 3 × 10⁵
  • -10⁹ ≤ nums[i], target ≤ 10⁹
  • nums is in order from smallest to largest: nums[i] ≤ nums[i + 1]

Watch the explanation

More Binary Search

All Binary Search problems