Find First and Last Position of a Value

MediumBinary Search

You are given an integer array nums sorted in non-decreasing order (values may repeat) and an integer target.

Return a pair [first, last]: the index of the first occurrence of target and the index of its last occurrence. If target does not appear, return [-1, -1].

Your solution must run in O(log n) time, even when the target fills most of the array.

Constraints

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

Examples

Example 1

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

The three 4s occupy indices 1, 2 and 3.

Example 2

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

5 is not in the array.

Example 3

Input: nums = [], target = 3
Output: [-1,-1]

An empty array contains nothing.

JavaScript you'll use: Numbers, Math and integer tricks Arrays: create, read, update

/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function searchRange(nums, target) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.