FastPrepFind First and Last Position in a Sorted Array

Find First and Last Position in a Sorted Array

Instacart logoInstacartâ—Ź MediumFULLTIMEPHONE SCREEN

Problem statement

You are given an integer array nums sorted in non-decreasing order and an integer target. Return the first and last index where target appears, as [first, last].

Indices start at 0. If target appears only once, first and last are the same index. If target is not in nums, return [-1,-1].

Follow-up: can you find both indices in O(log n) time?

Function

searchRange(nums: int[], target: int) → int[]

Examples

Example 1

nums = [5,7,7,8,8,10]target = 8return = [3,4]

The value 8 appears at indices 3 and 4.

Example 2

nums = [5,7,7,8,8,10]target = 6return = [-1,-1]

6 is not in the array, so the answer is [-1,-1].

Example 3

nums = []target = 0return = [-1,-1]

The array is empty, so 0 cannot be found.

Constraints

  • 0 <= nums.length <= 2000
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order.
  • -10^9 <= target <= 10^9

More Instacart problems

See Instacart hiring insights
Saved
public int[] searchRange(int[] nums, int target) {
    // Write your code here.
}
Checking account…