Search in Rotated Sorted Array

Find a number in a sorted array that was rotated, by looking at only a few of its positions.

An array of distinct integers was sorted in ascending order and then rotated at an unknown point: the numbers from some position to the end were moved, in order, to the front. So [0, 1, 2, 4, 5, 6, 7] might have become [4, 5, 6, 7, 0, 1, 2]. Given the rotated array nums and a number target, return the index of target in nums, or -1 if it is not there. For an array of n numbers, the search must run in O(log n) time, so it may look at only a few positions, not at every number.

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

The Idea

Think of a shelf of numbered books in order: 0, 1, 2, 4, 5, 6 and 7. Someone takes the last four books, 4 to 7, and puts them in front of the others. The shelf now reads 4, 5, 6, 7, 0, 1, 2. Each of the two parts is still in order, but the whole row is not.

How would you find book 0 on a shelf that is fully in order? You would not check every book. You would look at the middle book. If 0 is smaller than its number, book 0 must be to the left, and the right half can be ignored; if 0 is bigger, the left half goes instead. Each look throws away half of what is left, so seven books need at most three looks. Halving the range on every look is the idea of binary search, and it is where O(log n) comes from: the number of looks grows like log2 n.

On the rotated shelf, that comparison goes wrong. The middle of 4, 5, 6, 7, 0, 1, 2 is 7. The target 0 is smaller, so plain binary search would go left, yet 0 sits on the right. So what can the middle number still tell us?

Look at where the order breaks. From left to right, the numbers rise up to 7, fall to 0, and rise again. Call that fall the drop. A rotated array has only one drop, so when the range is cut at the middle, at most one half contains it. The other half has no drop, which means that half is sorted.

A sorted half is easy to question: its smallest number is at its left end and its largest at its right end. If the target lies between those two, it can only be in that half; if not, it can only be in the other half. Either way, half the range goes, just as on a shelf in order. Look at the picture below, which searches Example 1 for 0.

Searching for 0 in 4, 5, 6, 7, 0, 1, 2. Step 1: mid is 7, the left half 4..7 is sorted and 0 is not in it, so the search goes right. Step 2: mid is 1, the left half 0..1 is sorted and 0 is in it, so the search goes left. Step 3: mid is 0, found at index 4.

The dashed line marks the drop, between 7 and 0. In the row labelled step 1, the markers lo and hi sit at the two ends of the range, and mid at its middle position, holding 7. The drop is to the right of mid, so the left half 4..7 is sorted. 0 is not between 4 and 7, so the search goes right.

In step 2, the range is 0, 1, 2 and mid holds 1. The left half 0..1 is sorted and 0 is in it, below 1, so the search goes left. In step 3, lo, mid and hi all point at index 4, and 0 is found there. Three looks, and the rotation never had to be undone.

Solution Approach

A simple scan already finds the target, so the task is to beat it with halving, which means settling three things: how to tell which half is sorted, which half to keep, and when to stop.

The simple scan

Why not just check every number? A loop from the first index to the last finds 0 at index 4 in Example 1, and returns -1 if it reaches the end. It is correct, but it may look at all n numbers, so a million numbers can take a million checks. Halving needs about 20 looks for a million numbers, because 220 is just over a million.

Telling which half is sorted

How do we know, from the numbers alone, which half has no drop? Compare the first number of the range with the middle one. If nums[lo] <= nums[mid], the numbers rise all the way from lo to mid, so the left half nums[lo..mid] is sorted. Otherwise the drop lies between lo and mid, and the right half nums[mid..hi] is sorted.

Why <= and not <? When the range holds two numbers, mid lands on lo, and the left half is that single number. One number on its own counts as sorted, and <= says so, because nums[lo] and nums[mid] are then the same number. Since the numbers are distinct, they are equal only in this case.

Choosing the half to keep

Once we know which half is sorted, which half do we keep? For a sorted left half, the target is inside it when nums[lo] <= target < nums[mid]. The test uses < at nums[mid], because the middle number was already compared with the target. If the test passes, hi moves to mid - 1; if not, lo moves to mid + 1.

A sorted right half works the other way round. When nums[mid] < target <= nums[hi], the search keeps the right half with lo = mid + 1, and otherwise keeps the left half with hi = mid - 1.

When to stop

When does the search end? Each pass first checks whether nums[mid] is the target, and returns mid if it is. Otherwise the range shrinks by at least one position, so sooner or later it becomes empty, with lo past hi. An empty range means the target is nowhere in the array, and the answer is -1.

Java Solution

The method search works in these steps:

  1. First, set lo to 0 and hi to nums.length - 1, so the range covers the whole array.
  2. Loop while lo <= hi, that is, while the range still holds at least one number. Each pass computes the middle position mid as lo + (hi - lo) / 2. Unlike (lo + hi) / 2, this never adds two large indexes together, so it cannot go past the int range on a huge array.
  3. If nums[mid] equals target, return mid.
  4. If nums[lo] <= nums[mid], the left half is sorted. Keep it with hi = mid - 1 when nums[lo] <= target < nums[mid], and otherwise move lo to mid + 1.
  5. Otherwise the right half is sorted. Keep it with lo = mid + 1 when nums[mid] < target <= nums[hi], and otherwise move hi to mid - 1.
  6. If the loop ends without finding target, return -1.

The main method runs both examples, a rotation whose right half is the sorted one, an array that was never rotated, a two-number array, and a one-number array searched for a number it has and one it lacks. A small helper, show, prints each array, the target and the result.

Java
import java.util.Arrays;

public class SearchInRotatedSortedArray {

    public static int search(int[] nums, int target) {
        int lo = 0;
        int hi = nums.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            if (nums[lo] <= nums[mid]) {                    // left half nums[lo..mid] is sorted
                if (nums[lo] <= target && target < nums[mid]) {
                    hi = mid - 1;                           // target is in the sorted left half
                } else {
                    lo = mid + 1;
                }
            } else {                                        // right half nums[mid..hi] is sorted
                if (nums[mid] < target && target <= nums[hi]) {
                    lo = mid + 1;                           // target is in the sorted right half
                } else {
                    hi = mid - 1;
                }
            }
        }
        return -1;
    }

    static void show(int[] nums, int target) {
        System.out.println(Arrays.toString(nums) + ", target " + target + " -> "
                + search(nums, target));
    }

    public static void main(String[] args) {
        int[] nums = {4, 5, 6, 7, 0, 1, 2};
        show(nums, 0);
        show(nums, 3);
        show(new int[] {6, 7, 1, 2, 3, 4, 5}, 7);
        show(new int[] {1, 2, 3, 4, 5}, 4);
        show(new int[] {3, 1}, 1);
        show(new int[] {1}, 1);
        show(new int[] {1}, 0);
    }
}

Running it prints:

Output
[4, 5, 6, 7, 0, 1, 2], target 0 -> 4
[4, 5, 6, 7, 0, 1, 2], target 3 -> -1
[6, 7, 1, 2, 3, 4, 5], target 7 -> 1
[1, 2, 3, 4, 5], target 4 -> 3
[3, 1], target 1 -> 1
[1], target 1 -> 0
[1], target 0 -> -1

Example 1 gives 4, the index of 0, and Example 2 gives -1, since 3 is not in the array. Look at the third line. In [6, 7, 1, 2, 3, 4, 5] the first middle number is 2, and nums[0], which is 6, is bigger, so the right half 2..5 is the sorted one. 7 is not in 2..5, so the search goes left and finds 7 at index 1 on the next pass.

The fourth line shows that an array that was never rotated is simply sorted. There nums[lo] <= nums[mid] always holds, so the method acts like plain binary search and finds 4 at index 3.

The fifth line, [3, 1] with target 1, depends on the <= in nums[lo] <= nums[mid]. Here mid is 0, the same position as lo. With < instead, the left half would count as unsorted, the right-half test 3 < 1 would fail, and the search would end. That version, run on [3, 1], prints -1, while the code above prints 1.

The last two lines search the one-number array [1]. Target 1 is found at index 0 on the first pass. Target 0 is not, so the range becomes empty after that pass and the method returns -1.

Complexity

The work is the number of passes of the loop, and each pass does only a few comparisons.

  • Time: O(log n), because every pass either returns or throws away the half of nums[lo..hi] that cannot hold the target. A range of n numbers empties after about log2 n passes; the seven numbers of Example 1 needed three.
  • Space: O(1), because the rotation is never undone and nothing is copied. The search keeps only lo, hi and mid.

If the array can contain repeated numbers, the check nums[lo] <= nums[mid] can no longer tell which half is sorted; Search in Rotated Sorted Array II shows how to handle that. To find the position of the drop itself, see Find Minimum in Rotated Sorted Array.