Find First and Last Position of Element in Sorted Array

Medium · Binary Search · Array · Binary Search

Problem

nums is sorted in non-decreasing order, so equal values sit next to each other. Return [first, last]: the first and the last index at which target appears. If it does not appear, return [-1, -1].

The search must take O(log n) time, even when target fills most of the array. Finding one copy and walking left and right from it is not enough: with a hundred thousand copies, that walk is a hundred thousand steps.

Examples

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

The two 8s sit at indices 3 and 4.

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

6 would go between the 5 and the first 7, but it is not there.

Constraints

Approaches

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…