Problem overview
The method search receives a vector<int> named nums of distinct integers and an integer target. The vector 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 when it isn't there.
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. The statement asks for O(log n) time and O(1) extra space, with up to a million elements.
Approach: one half is always sorted
A linear scan finds the target in O(n), which ignores the sorted structure. Plain binary search needs a fully sorted vector, and a rotated vector isn't one: the values rise, drop once at the rotation point, then rise again.
The key observation is that if you look at the middle element, at least one of the two halves around it is sorted. The values drop only once, at the rotation point, so the drop falls in at most one half, and the other half rises from end to end.
That is enough to keep halving the search window:
- Check the middle element. If it is the target, return its index.
- Work out which half is sorted. If
nums[left] <= nums[middle], the left half is sorted. Otherwise the right half is. - In a sorted half, two comparisons with its ends tell you whether the target can be in it. If it can, keep that half. If not, the target can only be in the other half, sorted or not, so keep that one.
Each pass throws away half of the window, so the loop runs about log2 n times.
For example, in [6, 7, 1, 2, 3, 4, 5] with target 7, the middle element is nums[3] = 2. The half from the middle to the end, [2, 3, 4, 5], is sorted, and 7 is not between 2 and 5. So 7 can only be in the left part, and the search continues there.
Step by step
- Declare
leftandrightasints on one line: 0 andnums.size() - 1. Both ends are inclusive: the window is everything fromlefttoright. - Loop while
left <= right. Use<=, because when the two are equal one element is still unchecked. - Compute
middleasleft + (right - left) / 2. Integer division rounds down, and adding half the distance toleftcan't overflow the way(left + right) / 2could for very large indices. - Return
middleifnums[middle] == target. After this check, the other steps only decide which half to drop. - Test whether the left half is sorted:
nums[left] <= nums[middle]. The<=matters: whenleftequalsmiddle, the left half is one element, and one element is sorted. - Inside it, test whether the target lies in that half:
nums[left] <= target && target < nums[middle]. The upper bound is strict becausenums[middle]was already checked. If so,right = middle - 1. - Otherwise move
left = middle + 1: the target isn't in the sorted left half, so it can only be in the right one. - In the outer
else, the left half isn't sorted, so the right half, frommiddletoright, is. - Test whether the target lies in the right half:
nums[middle] < target && target <= nums[right]. If so,left = middle + 1. - Otherwise
right = middle - 1. - After the loop, return
-1. The window is empty, so every index that could hold the target was ruled out.
The solution in C++
class Solution {
public:
int search(vector<int> &nums, int target) {
int left = 0, right = nums.size() - 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 C++ details worth knowing:
rightis signed on purpose.nums.size()is unsigned, but the result ofnums.size() - 1is stored in anint. Searches like this one move boundaries withmiddle - 1andmiddle + 1, and the usual loop testleft <= rightrelies on ordinary signed arithmetic. With unsigned variables,0 - 1would wrap to a huge number instead of -1, and a bound like that could send the loop off the end of the vector.- One declaration, two variables.
int left = 0, right = nums.size() - 1;declares twoints, each with its own initial value. - The vector is a reference.
vector<int> &numsavoids copying up to a million elements. The search only reads it. - Integer division of two non-negative
ints truncates, so(right - left) / 2rounds down.
Tracing the examples
With nums = [4, 5, 6, 7, 0, 1, 2] and target = 0, the windows are:
| left | right | middle | nums[middle] | What happens |
|---|---|---|---|---|
| 0 | 6 | 3 | 7 | left half is sorted (4 to 7), 0 is not in it, so left = 4 |
| 4 | 6 | 5 | 1 | left half [0, 1] is sorted and 0 is in it, so right = 4 |
| 4 | 4 | 4 | 0 | found, return 4 |
With target = 3 the first two windows are the same. In the first, 3 is not in 4 to 7, so left = 4. In the second, the left half [0, 1] doesn't contain 3, so left = 6. The last window, left = 6, right = 6, has middle 6 and nums[6] = 2, which is not 3, and the window then empties, so the result is -1.
With nums = [6, 7, 1, 2, 3, 4, 5] and target = 7, the first window has middle = 3 and nums[3] = 2. The left half is not sorted, the right half [2, 3, 4, 5] is, and 7 is not in it, so right = 2. The window left = 0, right = 2 has middle = 1 and nums[1] = 7: found, return 1.
Complexity
Time is O(log n). Every pass either returns or drops at least half of the window, and each pass does a constant number of comparisons.
Extra space is O(1). The search uses three integers and no recursion.
Edge cases and common mistakes
- Not rotated. With
k = 0the vector is plain sorted, the left half is always the sorted one, and the code is ordinary binary search.[1, 2, 3, 4, 5]with target 5 returns 4. - One element.
[1]with target 1 returns 0, and with target 0 returns -1. - Two elements.
[3, 1]with target 1 returns 1, and[2, 1]with target 2 returns 0. This is the case that breaks a strict comparison: hereleftequalsmiddleat index 0, and the left half must count as sorted. - Using
<instead of<=innums[left] <= nums[middle]. Whenleft == middle, the half is wrongly treated as unsorted. With the strict version, searching for 1 in[3, 1]returns -1 instead of 1, and so does searching for 1 in[2, 1]. - Making the target test strict at both ends.
nums[left]can be the target, so the lower bound is<=. Only the end next tomiddleis strict, becausemiddlewas already checked. - Duplicates. This solution relies on the values being distinct. With duplicates,
nums[left] == nums[middle]no longer proves the left half is sorted, and the search needs extra handling. - Target absent. The target 3 in
[4, 5, 6, 7, 0, 1, 2]is not in the vector, and the loop ends with the window empty, giving -1.
