Find First and Last Position of Element in Sorted Array - 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
Example 1 — Basic Range
$
Input:
nums = [5,7,7,8,8,10], target = 8
›
Output:
[3,4]
💡 Note:
Target 8 appears at indices 3 and 4. The first occurrence is at index 3, last occurrence at index 4.
Example 2 — Target Not Found
$
Input:
nums = [5,7,7,8,8,10], target = 6
›
Output:
[-1,-1]
💡 Note:
Target 6 is not present in the array, so return [-1, -1].
Example 3 — Single Element
$
Input:
nums = [], target = 0
›
Output:
[-1,-1]
💡 Note:
Empty array, target cannot be found.
Constraints
- 0 ≤ nums.length ≤ 105
- -109 ≤ nums[i] ≤ 109
- nums is a non-decreasing array
- -109 ≤ target ≤ 109
Visualization
Tap to expand
Understanding the Visualization
1
Input
Sorted array [5,7,7,8,8,10] and target 8
2
Search
Binary search to find first and last occurrences
3
Output
Return range [3,4] or [-1,-1] if not found
Key Takeaway
🎯 Key Insight: Binary search twice - once for leftmost boundary, once for rightmost boundary
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code