Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

First and Last Position

Searchingmedium

Given a sorted array `nums`, implement `searchRange(nums, target)` returning `[first, last]` indices of `target`, or `[-1, -1]` if absent.

Sample tests

Input: searchRange([5,7,7,8,8,10], 8)
Output: [3,4]
Input: searchRange([5,7,7,8,8,10], 6)
Output: [-1,-1]

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • A single search finds some match but not necessarily the first or last.

Learning resources

  • Wikipedia: Binary search
Approach & explanation (try first)

Two boundary binary searches locate the first and last index in O(log n) time.

Loading...
⌘/Ctrl + Enter

Run your code to see results.