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 nums sorted in non-decreasing order, so each number is at least as large as the one before it and repeats are allowed, return the first and last index of target. If target is not in the array, return [-1, -1]. The search must run in O(log n) time, where n is the length of the array: the number of steps may grow only with the number of times n can be halved.

Example 1
Input: nums = [5, 7, 7, 8, 8, 10], target = 8
Output: [3, 4]
Example 2
Input: nums = [5, 7, 7, 8, 8, 10], target = 6
Output: [-1, -1]
Example 3
Input: nums = [], target = 0
Output: [-1, -1]
Solution

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]. No folder is labelled 6, so Example 2 gives [-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.

The array 5, 7, 7, 8, 8, 10 with two rows of answers. For value >= 8, the answers are no, no, no, yes, yes, yes, and the first yes is at index 3, the first 8. For value > 8, only index 5 says yes, so the last 8 is one before it, at index 4.

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, lo and hi, and the first yes always lies somewhere from lo up to hi. lo starts at 0. hi starts at nums.length, one past the last index, because a row may have no yes at all. For target 11, every value answers no to "value >= 11?", and the search must be able to say "position 6".

Each round looks at the position mid halfway between them. If the answer there is no, the first yes is further right, so lo becomes mid + 1. If it is yes, mid may itself be the first yes, so hi becomes mid and keeps it in range. When lo and hi meet, they are on the first yes.

For "value >= 8?" this goes: lo 0 and hi 6 give mid 3, the value 8 says yes, and hi becomes 3. Then mid 1 holds 7, a no, so lo becomes 2. Then mid 2 holds 7, so lo becomes 3, meets hi, and the search returns 3.

The middle is computed as lo + (hi - lo) / 2 rather than (lo + hi) / 2. On a very large array, lo + hi could pass the largest value an int can hold, while hi - lo never does.

The second question

What changes for the last 8? Only the question. The first search, firstAtLeast, treats a value as no when nums[mid] < target. The second, firstGreater, treats it as no when nums[mid] <= target, so the 8s become no as well. It lands on the first value larger than 8, index 5, and the last 8 is one place before it.

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? firstAtLeast always returns some position. For target 6 it returns 1, the first value at least 6, but nums[1] is 7. For target 11 it returns 6, past the end, and reading nums[6] would throw an ArrayIndexOutOfBoundsException. So the code first checks whether the position found equals nums.length, then whether the value there equals the target. If either check fails, the answer is [-1, -1], and the second search is not needed.

Java Solution

The method searchRange works in these steps:

  1. First, find the first index whose value is at least target with firstAtLeast(nums, target), and store it in first. Inside the helper, lo starts at 0 and hi at nums.length. A loop runs while lo < hi: it picks mid, moves lo to mid + 1 when nums[mid] < target, and otherwise moves hi to mid. The helper returns lo.
  2. If first equals nums.length, or nums[first] is not target, return [-1, -1].
  3. Otherwise, find the first index whose value is larger than target with firstGreater(nums, target). It runs the same loop, with <= in place of <. One less than its result is last.
  4. Return [first, last].

The main method runs the three examples, a target larger than every value, an array that holds only the target, and Integer.MAX_VALUE, the largest int, as the target.

Java
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:

Output
[3, 4]
[-1, -1]
[-1, -1]
[-1, -1]
[0, 2]
[1, 1]

The opening [3, 4] and the two [-1, -1] lines after it match the examples. For the empty array, lo and hi both start at 0, the loop never runs, and first is 0, which equals nums.length. The fourth line is target 11: first comes back as 6, and the length check returns before nums[6] is read. The fifth line, [0, 2], comes from [2, 2, 2]: every element is the target, so the range covers the whole array.

Look at the last line, [1, 1]. It guards against a tempting shortcut: drop firstGreater and compute the last index as firstAtLeast(nums, target + 1) - 1. When target is 2,147,483,647, the largest int, adding 1 goes past the limit. An int that does that wraps around to the most negative value, -2,147,483,648, which is called overflow. Every element counts as at least that, so the shortcut's search returns 0 and the answer becomes [1, -1]. firstGreater never adds 1 to the target, so it gets [1, 1] right.

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 lo to hi, so one search over n elements ends after about log₂ n rounds, 20 for a million. The second search doubles that at most.
  • Space: O(1), because each helper keeps only lo, hi and mid, and the answer is a fixed array of two numbers.

The number of times the target appears is last - first + 1, so it comes in O(log n) as well. firstAtLeast on its own solves Search Insert Position.