Find First and Last Position of Element in Sorted Array

Medium#34both edges

You get an array sorted in non-decreasing order, so equal numbers stand together, and a target. Return the first and the last index of the target, or [−1, −1] if it is not there, in O(log n) time. Our example: [1, 3, 3, 3, 3, 3, 6, 8] and 3 — the answer is [1, 5].

input
nums: integers in non-decreasing order, maybe none; target: an integer.
returns
The first and the last index of target in nums, [first, last], or [-1, -1] if it is not there. LeetCode wants it in O(log n).
constraints
  • 0 ≤ nums.length ≤ 10⁴
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • nums is in non-decreasing order
  • −10⁴ ≤ target ≤ 10⁴
our 13 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number[]}
 */
function searchRange(nums, target) {

}
Ctrl ↵
format
reset

saved in this browser

13 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more binary search problems

Pattern “Binary search” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.