Find First and Last Position of Element in Sorted Array
Locate the starting and ending indices of a target value block in an array with duplicates in O(log n) time using two lower-bound binary searches.
01The problem
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity.
| Input | Output | Why |
|---|---|---|
nums = [5, 7, 7, 8, 8, 10], target = 8 | [3, 4] | 8 begins at index 3 and ends at index 4 |
nums = [5, 7, 7, 8, 8, 10], target = 6 | [-1, -1] | 6 does not exist in the array |
nums = [], target = 0 | [-1, -1] | Empty array has no elements |
nums = [1], target = 1 | [0, 0] | Single element matching target |
Constraints: 0 to 100,000 numbers, sorted ascending with duplicates allowed.
Loading the rest of the lesson…