Problem overview
The function search receives a vector of distinct integers, nums, and a 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 function returns the index of target, or -1 if it isn't there, in O(log n) time and O(1) space.
In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is missing, so the answers are 4 and -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 works in O(n), but the problem asks for O(log n), which means binary search. A plain binary search assumes the whole vector is sorted, and a rotated one isn't. On [4, 5, 6, 7, 0, 1, 2] with target 0, a plain search looks at the middle value 7, sees that 7 is bigger than 0, and discards the right half, where 0 actually is. It returns -1.
The key observation is that the values drop only once, at the rotation point. So around any middle, the drop falls into at most one of the two halves, and the other half is sorted from end to end. For a sorted half, two comparisons with its ends tell whether target can be in it. If it can, keep that half; otherwise, keep the other one. Either way, half of the window is discarded, so there are about log₂ n passes.
The test for a sorted left half is nums[left] <= nums[middle]. If it fails, the right half, from middle to right, is the sorted one.
Here is the search for 0 in [4, 5, 6, 7, 0, 1, 2]:
left=0 right=6 middle=3 nums[middle]=7
left=4 right=6 middle=5 nums[middle]=1
left=4 right=4 middle=4 nums[middle]=0
found 4
In the first pass, the left half [4, 5, 6, 7] is sorted and 0 isn't between 4 and 7, so left moves to 4. In the second pass the window is [0, 1, 2], which is sorted, and 0 is at least nums[left] and smaller than nums[middle], so right moves to 4. The third pass finds 0 at index 4.
Step by step
- Declare
leftandrightas mutable variables: 0 andnums.len() - 1. Both ends are inclusive, and the vector is never empty, so the subtraction is safe. - Loop while
left <= right. When they are equal, one element is still unchecked. - Compute
middleasleft + (right - left) / 2. Integer division already rounds down, and this form can't overflow, unlike halvingleft + right. - Return
middle as i32ifnums[middle]equalstarget. The cast converts theusizeindex to the function'si32. - Test whether the left half is sorted:
nums[left] <= nums[middle]. The<=covers the case whereleftequalsmiddle, a half of one element. - In a sorted left half, if
nums[left] <= targetandtarget < nums[middle], the target is inside it: setrighttomiddle - 1. - Otherwise drop the left half: set
lefttomiddle + 1. - The
elseof the outer test: the left half isn't sorted, so the right half is. - In a sorted right half, if
nums[middle] < targetandtarget <= nums[right], the target is inside it: setlefttomiddle + 1. - Otherwise the target can only be in the left half: set
righttomiddle - 1. - After the loop, every index has been ruled out, so end the function with
-1.
The solution in Rust
impl Solution {
fn search(nums: Vec<i32>, target: i32) -> i32 {
let mut left = 0;
let mut right = nums.len() - 1;
while left <= right {
let middle = left + (right - left) / 2;
if nums[middle] == target {
return middle as i32;
}
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;
}
}
}
-1
}
}
The Rust details worth a closer look:
usizeindexes.leftandrightget the typeusizefromnums.len() - 1and from indexing. Ausizecan't be negative, somiddle - 1must never be computed whenmiddleis 0. Both places that do it are safe: in the first,nums[left] < nums[middle]holds (the target is at leastnums[left]and smaller thannums[middle]), somiddleis pastleft; in the second, the unsorted left half meansnums[left] > nums[middle], which again putsmiddlepastleft.- The cast on return.
middle as i32converts ausizeinto ani32. The vector has at most a million elements, so the value always fits. A cast between integer types never panics; it truncates silently if the value doesn't fit. left + (right - left) / 2. Sinceright >= leftinside the loop,right - leftcan't underflow.- The last expression.
-1without a semicolon is the function's value when the loop finishes without a return. - Indexing is checked. An out-of-range index panics rather than reading garbage, and the window logic keeps every index inside the vector.
Complexity
Time: O(log n). Each pass of the loop discards at least half of the window, so a vector of a million elements needs about 20 passes.
Space: O(1). The function keeps three indexes and never copies the vector.
Edge cases and common mistakes
- A vector that wasn't rotated.
[1, 2, 3, 4, 5]with target 4 gives 3. The left half is always sorted, and the search behaves like a normal binary search. - A single element.
[1]with target 1 gives 0, and with target 0 gives -1: the window becomes empty after one pass. - Two elements.
[3, 1]with target 1 gives 1. Hereleftequalsmiddle, and the left half is a single element, which counts as sorted because of the<=. With a strict<, the test would fail, the code would go to the other branch, andmiddle - 1would underflow theusizebecausemiddleis 0. - The target at an end.
[5, 1, 3]with target 5 gives 0, and[4, 5, 6, 7, 0, 1, 2]with target 2 gives 6. The comparisons withnums[left]andnums[right]are inclusive on the end that isn'tmiddle, so these are found. - Using a plain binary search. It gives -1 for target 0 in
[4, 5, 6, 7, 0, 1, 2], target 7 in[6, 7, 1, 2, 3, 4, 5]and target 1 in[3, 1], even though all three are present. - Using
left < rightas the loop condition. The loop would stop with one unchecked element left, and a target there would be reported as missing:[1]with target 1 would return -1. - Inclusive and exclusive comparisons. The target is compared with
nums[middle]strictly becausemiddlewas already checked for equality. The comparisons with the far end of the sorted half are inclusive, because that end hasn't been checked.
Testing
nums = [4, 5, 6, 7, 0, 1, 2],target = 0gives4.nums = [4, 5, 6, 7, 0, 1, 2],target = 3gives-1.nums = [6, 7, 1, 2, 3, 4, 5],target = 7gives1.nums = [1],target = 0gives-1.nums = [3, 1],target = 1gives1.nums = [5, 1, 3],target = 5gives0.
