Find First and Last Position of Element in Sorted Array

Medium

Topics
ArrayBinary Search

Given a sorted array nums and a target, return [first, last] — the first and last index of target. Return [-1, -1] if it is not found. Must run in O(log n).

Example 1

Input:  nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2

Input:  nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

Constraints

  • 0 <= nums.length <= 10^5
  • nums is sorted in non-decreasing order.
Run ⌘' · Submit ⌘⏎