Algorithm Day66 - Find First and Last Position of Element in Sorted Array
🧩 Problem Description
Given an array of integers nums
sorted in non-decreasing order, find the starting and ending position of a given target
value.
If the target is not found in the array, return [-1, -1]
.
You must write an algorithm with O(log n) runtime complexity.
💬 Examples
Example 1
1 | Input: nums = [5,7,7,8,8,10], target = 8 |
Example 2
1 | Input: nums = [5,7,7,8,8,10], target = 6 |
Example 3
1 | Input: nums = [], target = 0 |
💡 Intuition
Since the array is sorted, we can use binary search to find:
- The leftmost index of the target.
- The rightmost index of the target.
This avoids scanning linearly and ensures O(log n)
complexity.
🔢 Java Code (Binary Search)
1 | class Solution { |
⏱ Complexity Analysis
- Time: O(log n) — two binary searches.
- Space: O(1) — constant extra space.
✍️ Summary
- Use two binary searches to find the first and last occurrence.
- If target not found, return
[-1, -1]
.
Related problems
lc-35
— Search Insert Positionlc-704
— Binary Search