MediumArrayBinary Search

Find First and Last Position of Element in Sorted Array

LeetCode
1 approach, code in all languages

You are given an array of integers sorted in non-decreasing order along with a target value. Because the array can contain repeated numbers, the target may occupy a contiguous block of positions. Your job is to report the smallest index and the largest index at which the target appears.

If the target is not present anywhere in the array, return the pair [-1, -1]. The solution is expected to run in logarithmic time, so a straight linear scan does not meet the intended bound.

Example 1

Input: nums = [2, 4, 4, 4, 7, 9], target = 4

Output: [1, 3]

The value 4 first shows up at index 1 and last shows up at index 3, so the answer spans that range.

Example 2

Input: nums = [2, 4, 4, 4, 7, 9], target = 5

Output: [-1, -1]

The value 5 never appears in the array, so there is no valid range and we return [-1, -1].

Constraints

  • 0 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • nums is sorted in non-decreasing order
  • -10^9 <= target <= 10^9
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now