Problem overview
The method findMin(nums) receives an array of distinct integers that 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 smallest element. The statement asks for O(log n) time and O(1) extra 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 whole array, or calling Math.min on it, finds the minimum in O(n). To reach O(log n) the search must discard half of the array on every step, as in binary search, using the shape of a rotated array: a rising run, a single drop, and another rising run. The minimum is the element right after the drop, or the first element when there is no drop.
Compare nums[middle] with nums[right]:
- If
nums[middle] > nums[right], the values must drop somewhere between them, because in a sorted stretch the middle would be smaller than the last element. The minimum lies to the right ofmiddle, andmiddleitself can't be it, so movelefttomiddle + 1. - Otherwise
nums[middle] < nums[right](the values are distinct), so the stretch frommiddletorightis sorted. The minimum is atmiddleor to its left. Moverighttomiddle, keepingmiddlein the window, since it may be the answer.
Every pass keeps the minimum inside the window [left, right] and shrinks it, so the loop ends when one index is left, and that index holds the minimum.
The right-hand side is the right thing to compare with. Comparing with nums[left] fails on arrays that were not rotated, where the middle is bigger than nums[left] and yet the minimum is on the left.
On [4, 5, 6, 7, 0, 1, 2] the search goes like this:
| left | right | middle | nums[middle] | nums[right] | action |
|---|---|---|---|---|---|
| 0 | 6 | 3 | 7 | 2 | 7 > 2: left = 4 |
| 4 | 6 | 5 | 1 | 2 | 1 < 2: right = 5 |
| 4 | 5 | 4 | 0 | 1 | 0 < 1: right = 4 |
Now left and right are both 4, and nums[4] is 0. For [11, 13, 15, 17] the middle is never bigger than the last element, so right keeps moving left until it reaches index 0, and the answer is 11.
Step by step
- Declare
leftandrightwith onelet: 0 andnums.length - 1. The minimum can be anywhere, so the window starts as the whole array. - Loop while
left < right. This time it is<, not<=: the loop stops when one index is left, and that index holds the minimum. - Compute
middleasMath.floor(left + (right - left) / 2). The division may give a fraction, and an index has to be whole. - If
nums[middle] > nums[right], movelefttomiddle + 1. The middle value is bigger than another element, so it can't be the minimum. - Otherwise move
righttomiddle, notmiddle - 1, becausenums[middle]might be the minimum. - Return
nums[left]after the loop, whenleftandrightmeet.
The solution in JavaScript
class Solution {
findMin(nums) {
let left = 0, right = nums.length - 1;
while (left < right) {
let middle = Math.floor(left + (right - left) / 2);
if (nums[middle] > nums[right]) {
left = middle + 1;
} else {
right = middle;
}
}
return nums[left];
}
}
Some JavaScript details worth knowing:
- Division keeps the fraction.
7 / 2is3.5, not 3, so the midpoint needsMath.floorbefore it is used as an index.Math.floorrounds down, which is what keepsmiddlefrom reachingrightwhileleft < right. That matters:right = middleonly makes progress ifmiddleis belowright. - One
letfor two variables.let left = 0, right = nums.length - 1;declares both, and both are reassigned in the loop. - The result is a value, not an index. The function returns
nums[left]. Returningleftwould give the position of the minimum, which is the rotation point. - Reading out of range gives
undefined. For an empty array,nums[0]isundefined, and this function returns that. The constraints promise at least one element.
Complexity
Time: O(log n). Each pass at least halves the window: it either moves left past middle or pulls right in to middle, and both discard about half of the elements. For a million elements that is about 20 passes.
Space: O(1). Only three indices are stored.
Edge cases and common mistakes
- A single element.
[1]never enters the loop, and the function returns 1. - Two elements.
[2, 1]and[1, 2]both return 1. For[2, 1]the middle is index 0 and 2 is bigger than 1, soleftmoves to 1. - No rotation.
[1, 2, 3, 4]returns 1 and[11, 13, 15, 17]returns 11. The minimum is the first element, andrightmoves toward it. - Rotation by one in each direction.
[5, 1, 2, 3, 4]and[2, 3, 4, 5, 1]both return 1. - Negative numbers.
[-3, -2, -9, -7, -5]returns -9. Only comparisons are used, so signs don't matter. - Comparing with
nums[left]. Replacingnums[right]withnums[left]in the test gives 15 for[11, 13, 15, 17]and 2 for[4, 5, 6, 7, 0, 1, 2], both wrong. - Using
right = middle - 1. This can discard the minimum itself. For[3, 1, 2]that version returns 3 instead of 1. - Using
left <= right. Withright = middlethe window may stop shrinking whenleftequalsright, so the loop would never end. The condition must beleft < right. - Duplicates. The statement guarantees distinct values. With duplicates,
nums[middle]can equalnums[right]and the comparison no longer says which side holds the drop.
Testing
[3, 4, 5, 1, 2]gives1.[4, 5, 6, 7, 0, 1, 2]gives0.[11, 13, 15, 17]gives11.[1]gives1.[2, 1]gives1.[3, 1, 2]gives1.[-3, -2, -9, -7, -5]gives-9.
