All problemsBack
Find First and Last Position of Element in Sorted Array
mediumGiven 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.
Test Cases
Copy an input into themain harness and Run to verifyInput
nums = [5,7,7,8,8,10], target = 8Expected Output
[3,4]Input
nums = [5,7,7,8,8,10], target = 6Expected Output
[-1,-1]Input
nums = [], target = 0Expected Output
[-1,-1]Constraints
- 0 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums is sorted in non-decreasing order.
- -10^9 <= target <= 10^9
Hints
Hint 1 — click to reveal
Once you find any occurrence, scanning outward is O(n) when the array is all the same value.
Hint 2 — click to reveal
Run binary search twice: once biased toward the left edge, once toward the right.
Java Compiler
Powered by OneCompiler. Starter code loads automatically — edit and hit Run.