Find First and Last Position in Sorted Array
Find where a value starts and ends in a sorted array, with two binary searches.
Given an array of integers numstargettarget[-1, -1]
Example 1
Output: [3, 4]
Example 2
Output: [-1, -1]
Example 3
Output: [-1, -1]
The Idea
Picture a shelf of folders sorted by number: 5, 7, 7, 8, 8, 10. You want every folder labelled 8, so you need to know where the run of 8s starts and where it ends. Counting positions from 0, the 8s are at positions 3 and 4, so the answer for Example 1 is [3, 4][-1, -1]
Checking each folder in turn works, but it takes as many steps as there are folders. A sorted array allows something faster, called binary search. Look at the middle element: everything left of it is smaller or equal, and everything right of it is larger or equal. So one look tells you which half cannot hold what you want, and you throw that half away. Each look halves what is left, so a million elements need only about 20 looks.
Plain binary search answers a different question, though: "is there an 8, and where is one?" It stops at whichever 8 the middle happens to land on. In the example that could be index 3 or index 4, and in an array of a thousand 8s it could be any of them. Walking left and right from there to find the ends costs one step per 8. So how can binary search find the edges of the run, not just some element inside it?
By asking a yes/no question about each element, one whose answer flips only once. Look at the picture below.
In the row labelled "value >= 8?", the answer is no for 5, 7 and 7, then yes from index 3 on. Because the array is sorted, once the answer turns to yes it stays yes. The first yes, at index 3, is exactly the first 8.
In the row labelled "value > 8?", the 8s now answer no too, and the first yes is at index 5, the 10. The last 8 sits one place before it, at index 4. So each end of the run is the place where a row of answers turns from no to yes. Binary search can find that place, because the answer in the middle tells which half holds the turn.
Solution Approach
Turning that idea into code means settling three things: how to find the first yes in a row of answers, how the second question differs from the first, and how to tell that the target is missing.
Finding the first yes
How does a binary search find the first yes? It keeps two positions, lohilohilohinums.length
Each round looks at the position midlomid + 1midhimidlohi
For "value >= 8?" this goes: lohimidhimidlomidlohi
The middle is computed as lo + (hi - lo) / 2(lo + hi) / 2lo + hiinthi - lo
The second question
What changes for the last 8? Only the question. The first search, firstAtLeastnums[mid] < targetfirstGreaternums[mid] <= target
Both searches find a place in the array where a value could be inserted while keeping it sorted. The first is often called the lower bound of the target and the second its upper bound.
When the target is missing
How do we know the target is there at all? firstAtLeastnums[1]nums[6]ArrayIndexOutOfBoundsExceptionnums.length[-1, -1]
Java Solution
The method searchRange
- First, find the first index whose value is at least
withtarget , and store it infirstAtLeast(nums, target) . Inside the helper,first starts at 0 andlo athi . A loop runs whilenums.length : it pickslo < hi , movesmid tolo whenmid + 1 , and otherwise movesnums[mid] < target tohi . The helper returnsmid .lo - If
equalsfirst , ornums.length is notnums[first] , returntarget .[-1, -1] - Otherwise, find the first index whose value is larger than
withtarget . It runs the same loop, withfirstGreater(nums, target) in place of<= . One less than its result is< .last - Return
.[first, last]
The mainInteger.MAX_VALUEint
import java.util.Arrays;
public class FirstAndLastPosition {
public static int[] searchRange(int[] nums, int target) {
int first = firstAtLeast(nums, target);
if (first == nums.length || nums[first] != target) {
return new int[] {-1, -1}; // target is not in the array
}
int last = firstGreater(nums, target) - 1; // one before the first larger value
return new int[] {first, last};
}
// First index whose value is >= target, or nums.length if there is none
private static int firstAtLeast(int[] nums, int target) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] < target) {
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
// First index whose value is > target, or nums.length if there is none
private static int firstGreater(int[] nums, int target) {
int lo = 0;
int hi = nums.length;
while (lo < hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] <= target) { // the only difference: <= instead of <
lo = mid + 1;
} else {
hi = mid;
}
}
return lo;
}
public static void main(String[] args) {
int[] nums = {5, 7, 7, 8, 8, 10};
System.out.println(Arrays.toString(searchRange(nums, 8)));
System.out.println(Arrays.toString(searchRange(nums, 6)));
System.out.println(Arrays.toString(searchRange(new int[] {}, 0)));
System.out.println(Arrays.toString(searchRange(nums, 11)));
System.out.println(Arrays.toString(searchRange(new int[] {2, 2, 2}, 2)));
int max = Integer.MAX_VALUE;
System.out.println(Arrays.toString(searchRange(new int[] {1, max}, max)));
}
}
Running it prints:
[3, 4]
[-1, -1]
[-1, -1]
[-1, -1]
[0, 2]
[1, 1]
The opening [3, 4][-1, -1]lohifirstnums.lengthfirstnums[6][0, 2][2, 2, 2]
Look at the last line, [1, 1]firstGreaterfirstAtLeast(nums, target + 1) - 1targetintint[1, -1]firstGreater[1, 1]
Complexity
The work is at most two binary searches, and nothing else in the method depends on the length of the array.
- Time: O(log n), because every round of a search halves the stretch from
tolo , so one search over n elements ends after about log₂ n rounds, 20 for a million. The second search doubles that at most.hi - Space: O(1), because each helper keeps only
,lo andhi , and the answer is a fixed array of two numbers.mid
The number of times the target appears is last - first + 1firstAtLeast