MediumArrayBinary Search

1 approach, code in every language

Problem description

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

After the pattern

Now solve one you haven't seen.

Deviation Value Span is our own problem on the technique behind Find First and Last Position of Element in Sorted Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free