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][4, 5, 6, 7, 0, 1, 2]numstargettargetnums
Example 1
Output: 4
Example 2
Output: -1
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.
The dashed line marks the drop, between 7 and 0. In the row labelled step 1, the markers lohimidmid
In step 2, the range is 0, 1, 2 and midlomidhi
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]lomidnums[lo..mid]lomidnums[mid..hi]
Why <=<midlo<=nums[lo]nums[mid]
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]<nums[mid]himid - 1lomid + 1
A sorted right half works the other way round. When nums[mid] < target <= nums[hi]lo = mid + 1hi = mid - 1
When to stop
When does the search end? Each pass first checks whether nums[mid]midlohi
Java Solution
The method search
- First, set
to 0 andlo tohi , so the range covers the whole array.nums.length - 1 - Loop while
, that is, while the range still holds at least one number. Each pass computes the middle positionlo <= hi asmid . Unlikelo + (hi - lo) / 2 , this never adds two large indexes together, so it cannot go past the(lo + hi) / 2 range on a huge array.int - If
equalsnums[mid] , returntarget .mid - If
, the left half is sorted. Keep it withnums[lo] <= nums[mid] whenhi = mid - 1 , and otherwise movenums[lo] <= target < nums[mid] tolo .mid + 1 - Otherwise the right half is sorted. Keep it with
whenlo = mid + 1 , and otherwise movenums[mid] < target <= nums[hi] tohi .mid - 1 - If the loop ends without finding
, return -1.target
The mainshow
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:
[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]nums[0]
The fourth line shows that an array that was never rotated is simply sorted. There nums[lo] <= nums[mid]
The fifth line, [3, 1]<=nums[lo] <= nums[mid]midlo<3 < 1[3, 1]
The last two lines search the one-number array [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
that cannot hold the target. A range of n numbers empties after about log2 n passes; the seven numbers of Example 1 needed three.nums[lo..hi] - Space: O(1), because the rotation is never undone and nothing is copied. The search keeps only
,lo andhi .mid
If the array can contain repeated numbers, the check nums[lo] <= nums[mid]