Problem
Given a sorted array that may contain duplicates, return the first and last index of a target value, or [-1, -1] if the target is not present. The search should run in O(log n) time.
Original: LeetCode 34: Find First and Last Position of Element in Sorted Array.
Examples
Example 1
`nums = [5, 7, 7, 8, 8, 10], target = 8``[3, 4]`Example 2
`nums = [5, 7, 7, 8, 8, 10], target = 6``[-1, -1]`Example 3
`nums = [], target = 0``[-1, -1]`Constraints
0 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9numsis a non-decreasing array.-10^9 <= target <= 10^9
Hints
Hint 1
Any-match binary search is not enough, because mid may land in the middle of a run. You want the two edges of that run. If the target is missing, both answers are -1, not an insertion point.
Hint 2
Boundary binary search: two lower bounds, one for the first index >= target and one for the first index >= target + 1.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. A linear scan that records the first and last hit: O(n).
Optimal. A shared lowerBound helper, the same half-open loop as Search Insert Position. left = lowerBound(nums, target). If left is n or nums[left] is not the target, return [-1, -1]. Otherwise the last index is lowerBound(nums, target + 1) - 1. target + 1 is safe here because the values fit in an int and you only use it as a search key; if you are uncomfortable with overflow, search for the first index strictly greater than target with a slightly different predicate.
Alternative. Two handwritten loops, one biased left and one biased right, also work, but they are easy to get off by one. Reusing lower bound is the cleaner interview answer.
Complexity
- Time
- O(log n)
O(log n) time, O(1) extra space.
- Space
- O(1)
Code
import java.util.Arrays;
public class FindFirstAndLastPosition {
static int[] searchRange(int[] nums, int target) {
int left = lowerBound(nums, target);
if (left == nums.length || nums[left] != target) return new int[] {-1, -1};
int right = lowerBound(nums, target + 1) - 1;
return new int[] {left, right};
}
static int lowerBound(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(searchRange(new int[] {5, 7, 7, 8, 8, 10}, 8))); // [3, 4]
System.out.println(Arrays.toString(searchRange(new int[] {5, 7, 7, 8, 8, 10}, 6))); // [-1, -1]
System.out.println(Arrays.toString(searchRange(new int[] {}, 0))); // [-1, -1]
}
}Edge cases
- Official samples: [5,7,7,8,8,10] with 8 returns [3,4]; with 6 returns [-1,-1].
- An empty array returns [-1,-1].
- A single matching element: first and last are the same index.
Follow-ups
- Count the occurrences: right - left + 1 after the same two searches.
- Search Insert Position is the lower bound by itself.
Interview script
"I find the first index that is at least the target, and the first index that is at least target + 1. If the first of those does not actually hold the target, I return [-1, -1]. Otherwise those two edges are the answer. Two logarithmic searches."
Source: LeetCode 34: Find First and Last Position of Element in Sorted Array