Problem overview
The method search receives an int[] nums of distinct integers and an int target. The array was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end. For example, [0, 1, 2, 4, 5, 6, 7] rotated at k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. The method returns the index of target, or -1 if it is not there. It must run in O(log n) time with O(1) extra space.
In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is missing, so the answer is -1. In [6, 7, 1, 2, 3, 4, 5], the target 7 is at index 1.
Approach: one half is always sorted
A linear scan solves the problem in O(n), but with up to a million elements the statement wants binary search. Plain binary search needs a fully sorted array, and a rotated array is not sorted: it rises, drops once at the rotation point, and rises again.
The idea of the lesson is that around any middle, at least one of the two halves is sorted. The values drop only once, so the drop lies in at most one half, and the other half rises from end to end. For a sorted half, two comparisons with its ends tell whether target can be inside it:
- If the left half (
lefttomiddle) is sorted,targetis in it exactly whennums[left] <= target < nums[middle]. - Otherwise the right half is sorted, and
targetis in it exactly whennums[middle] < target <= nums[right].
If the target is in the sorted half, keep that half. If not, keep the other one. Either way the window halves, which gives O(log n).
Trace for nums = [6, 7, 1, 2, 3, 4, 5] and target = 7:
| left | right | middle | nums[middle] | What happens |
|---|---|---|---|---|
| 0 | 6 | 3 | 2 | the left half is 6, 7, 1, 2, which is not sorted; the right half 2 to 5 is sorted and does not hold 7, so right moves to 2 |
| 0 | 2 | 1 | 7 | equals the target: return 1 |
Step by step
- Set the window.
left = 0andright = nums.length - 1. Both ends are inclusive. - Loop while
left <= right. With<=, a window of one element still gets checked. - Find the middle.
int middle = left + (right - left) / 2;Integer division rounds down. Adding half the distance toleftcannot overflow, unlike halving the sum. - Check for the target. If
nums[middle] == target, returnmiddle. This comes first, so the rest only decides which half to drop. - Is the left half sorted? Test
nums[left] <= nums[middle]. Use<=: whenleftequalsmiddle, the half is one element, and one element is sorted. - Inside a sorted left half. If
nums[left] <= target && target < nums[middle], the target is there, soright = middle - 1. The comparison withnums[middle]is strict, since that element was already checked. - Otherwise the target is not in the sorted left half, so
left = middle + 1. - Else, the right half is sorted. If
nums[middle] < target && target <= nums[right], the target is there, soleft = middle + 1. - Otherwise the target can only be in the left half:
right = middle - 1. - After the loop the window is empty and the target was not found, so return -1.
The solution in Java
class Solution {
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int middle = left + (right - left) / 2;
if (nums[middle] == target) {
return middle;
}
if (nums[left] <= nums[middle]) {
if (nums[left] <= target && target < nums[middle]) {
right = middle - 1;
} else {
left = middle + 1;
}
} else {
if (nums[middle] < target && target <= nums[right]) {
left = middle + 1;
} else {
right = middle - 1;
}
}
}
return -1;
}
}
The Java details worth a closer look:
- Declaring two ints at once.
int left = 0, right = nums.length - 1;declares both in one statement. - Integer division.
(right - left) / 2on twointvalues drops the fraction, so the middle of an even-length window is the lower of the two middle positions. - Why not
(left + right) / 2. In Java,intarithmetic wraps silently on overflow. Withleft = 1500000000andright = 2000000000,(left + right) / 2gives -397483648, whileleft + (right - left) / 2gives 1750000000. Arrays here are at most a million long, so the sum fits, but this form is a habit worth keeping. - Returning from inside a loop. The
return middle;ends the method at once. The finalreturn -1;is needed because the compiler rejects a method that could reach its end without returning anint. - Plain
intcomparisons. The elements are primitives, so==and<=compare values directly.
Complexity
Time: O(log n). Each pass of the loop discards at least half of the window, so the loop runs about log2 of n times, with constant work per pass.
Space: O(1). The method keeps three integers, left, right and middle, and builds nothing.
Edge cases and common mistakes
- One element.
[1]with target 1 gives 0, and with target 0 gives -1. - Using
left < right. With a window of one element, the loop would never check it. A version with that loop condition returns -1 for[1]with target 1, and also for[3, 1]with target 1. - Two elements. In
[3, 1]the target 1 is found at index 1. Whenmiddleequalsleft, the left half has one element, and the<=innums[left] <= nums[middle]correctly treats it as sorted. - An array that wasn't rotated.
[1, 2, 3, 4, 5]with target 4 gives 3. Rotation atk = 0is allowed, and then the left half is always the sorted one. - Target at the end of the range.
[1, 3, 5]with target 5 gives 2. The comparisons includenums[left]andnums[right]through<=, so the ends of a sorted half count as inside it. - Dropping
middletwice. Because the code already returned whennums[middle]was the target, the strict<againstnums[middle]is right, and moving tomiddle - 1ormiddle + 1always shrinks the window. - Duplicates. The method relies on distinct values. With repeated values,
nums[left] <= nums[middle]would no longer prove that the left half is sorted. The statement rules duplicates out.
Testing
nums = [4, 5, 6, 7, 0, 1, 2],target = 0gives 4.nums = [4, 5, 6, 7, 0, 1, 2],target = 3gives -1.nums = [6, 7, 1, 2, 3, 4, 5],target = 7gives 1.nums = [3, 1],target = 1gives 1.nums = [1, 2, 3, 4, 5],target = 4gives 3.nums = [1],target = 0gives -1.
