Problem overview
The function find_min receives a vector of distinct integers, nums, that was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end. With k = 3, [0, 1, 2, 4, 5, 6, 7] becomes [4, 5, 6, 7, 0, 1, 2], and with k = 0 the vector stays as it was. The function returns the smallest element, in O(log n) time and O(1) space.
For [3, 4, 5, 1, 2] the answer is 1, for [4, 5, 6, 7, 0, 1, 2] it is 0, and for the unrotated [11, 13, 15, 17] it is 11, the first element.
Approach: compare the middle with the last element
Scanning the vector takes O(n). For O(log n), use binary search on the window of indexes that can still hold the minimum, and decide at each step which half to discard.
The minimum is the element where the values drop, the rotation point (or the first element if there was no rotation). Compare nums[middle] with nums[right]:
- If
nums[middle] > nums[right], the values drop somewhere between them. In a sorted stretch every value is smaller than the last one, so a bigger middle means the rotation point lies to the right ofmiddle. Also,nums[middle]is bigger than another element, so it can't be the minimum. Movelefttomiddle + 1. - Otherwise
nums[middle] < nums[right](the values are distinct, so they are never equal whenmiddlediffers fromright). Everything frommiddletorightis sorted, so the minimum of that stretch isnums[middle]itself, and the global minimum is atmiddleor to its left. Moverighttomiddle, not tomiddle - 1, becausemiddlemay be the answer.
Each pass halves the window, and the loop ends when it has one index, which holds the minimum.
On [4, 5, 6, 7, 0, 1, 2] the window shrinks like this:
left=0 right=6 middle=3 nums[middle]=7 nums[right]=2
left=4 right=6 middle=5 nums[middle]=1 nums[right]=2
left=4 right=5 middle=4 nums[middle]=0 nums[right]=1
left=4 right=4 -> 0
Step by step
- Declare
leftandrightas mutable variables: 0 andnums.len() - 1. The minimum can be anywhere, so the window starts as the whole vector. The vector is never empty, so the subtraction is safe. - Loop while
left < right. It stops when the window is a single index, which is where the minimum is. - Compute
middleasleft + (right - left) / 2, which rounds down and can't overflow. - If
nums[middle] > nums[right], the minimum is to the right ofmiddle: setlefttomiddle + 1. - Otherwise the minimum is at
middleor to its left: setrighttomiddle. - After the loop,
leftandrightmeet at the minimum, so the function ends withnums[left].
The solution in Rust
impl Solution {
fn find_min(nums: Vec<i32>) -> i32 {
let mut left = 0;
let mut right = nums.len() - 1;
while left < right {
let middle = left + (right - left) / 2;
if nums[middle] > nums[right] {
left = middle + 1;
} else {
right = middle;
}
}
nums[left]
}
}
The Rust details worth a closer look:
usizeeverywhere.nums.len() - 1is ausize, soleftandrightare too, and they indexnumsdirectly. Neither is ever decreased below its starting value, so there is no underflow:leftonly grows andrightonly moves tomiddle, which is at leastleft.- The shortcut for the midpoint.
left + (right - left) / 2rounds down, somiddleis always less thanrightinside the loop. That is whyright = middleshrinks the window, and whyleft = middle + 1never passesright. - The value comes out of the vector by copy. The function returns
nums[left], ani32, which isCopy, so indexing the vector it owns is enough. There is no need forclone(). - Last expression.
nums[left]has no semicolon, so it is the function's value.
Complexity
Time: O(log n). Each pass at least halves the window.
Space: O(1). Only left, right and middle are stored.
Edge cases and common mistakes
- A vector that wasn't rotated.
[11, 13, 15, 17]gives 11. Every middle is smaller than the last element, sorightkeeps moving left until it reaches index 0. - A single element.
[9]gives 9: the loop doesn't run. - Two elements.
[2, 1]gives 1 and[1, 2]gives 1. For[2, 1],middleis 0,nums[0]is bigger thannums[1], andleftmoves to 1. - Comparing with
nums[left]instead ofnums[right]. In an unrotated vector,nums[middle]is bigger thannums[left], yet the minimum is on the left. A version that movesleftpastmiddlewhenevernums[middle] > nums[left]returns 15 for[11, 13, 15, 17], 2 for[4, 5, 6, 7, 0, 1, 2]and 3 for[5, 6, 7, 8, 9, 1, 2, 3, 4], all wrong. - Setting
right = middle - 1. Whennums[middle]is the minimum, this discards it. The assignment must keepmiddlein the window. - Using
left <= right. Withright = middleas the update, the window may stop shrinking whenleftequalsright, and the loop would never end. The strict<is what guarantees it stops. - Returning an index. The function returns the value
nums[left], not the indexleft.
Testing
nums = [3, 4, 5, 1, 2]gives1.nums = [4, 5, 6, 7, 0, 1, 2]gives0.nums = [11, 13, 15, 17]gives11.nums = [9]gives9.nums = [2, 1]gives1.nums = [5, 6, 7, 8, 9, 1, 2, 3, 4]gives1.
