Problem overview
The method findMin receives an array 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. It 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: the original array was [1, 2, 3, 4, 5], rotated by 2. For [11, 13, 15, 17], which was not rotated, the answer is its first element, 11.
Approach: compare the middle with the last element
Scanning every element finds the minimum in O(n). To get O(log n), use the shape of the array: its values rise, drop once at the rotation point, and rise again. The minimum is the first value after the drop, or the first element when there was no rotation.
Comparing nums[middle] with nums[right] tells which side of the window holds the drop:
- If
nums[middle] > nums[right], the values go down somewhere aftermiddle. The minimum is to the right, andmiddleitself can't be it, because it is bigger than another element. - Otherwise
nums[middle]is smaller thannums[right]and everything frommiddletorightis rising. The minimum is atmiddleor to its left.
Each pass drops about half of the window, and the loop stops when one index is left. Here is the search on [4, 5, 6, 7, 0, 1, 2]:
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
end left=4 right=4
In the first pass 7 is bigger than 2, so the minimum is to the right of index 3 and left becomes 4. In the second pass 1 is smaller than 2, so right moves to 5. In the third, 0 is smaller than 1, so right moves to 4, and the window is one index: nums[4], which is 0.
Step by step
- Set up the window.
leftandrightstart at 0 andnums.count - 1. The minimum can be anywhere, so the window is the whole array. Both arevarbecause the loop moves them. - Loop while
left < right. This time it is<, not<=: the loop stops when the window is a single index, and that index holds the minimum. - Compute
middleasleft + (right - left) / 2, alet. Integer division rounds down, and the form never overflows. - If
nums[middle] > nums[right], setleft = middle + 1. The drop lies betweenmiddleandright, so the minimum is pastmiddle. - Otherwise, set
right = middle. Notmiddle - 1:nums[middle]may be the minimum. - Return
nums[left]once the pointers meet.
The solution in Swift
class Solution {
func findMin(_ nums: [Int]) -> Int {
var left = 0, right = nums.count - 1
while left < right {
let middle = left + (right - left) / 2
if nums[middle] > nums[right] {
left = middle + 1
} else {
right = middle
}
}
return nums[left]
}
}
Swift details worth knowing:
- Two variables on one line.
var left = 0, right = nums.count - 1declares two separateIntvariables. - The result is not optional. The method returns
nums[left]as a plainInt. An empty array would makenums[left]an index error, and the constraints promise at least one element. - Integer division.
(right - left) / 2truncates, and sinceright - leftis positive inside the loop,middleis always strictly belowright. That is whyleft = middle + 1andright = middleboth shrink the window, and the loop always ends. - No unsafe arithmetic. Swift traps on overflow, and
left + (right - left) / 2keeps every intermediate value inside the array's index range.
Complexity
Time: O(log n). Each pass discards at least half of the window, so the loop runs about log base 2 of n times.
Space: O(1). Only left, right and middle are stored.
Edge cases and common mistakes
- No rotation.
[11, 13, 15, 17]returns 11. In every passnums[middle]is smaller thannums[right], sorightkeeps moving left until it reaches index 0. - One element.
[1]returns 1 without entering the loop. - Two elements.
[2, 1]returns 1 and[1, 2]returns 1. - Rotated by one or by almost the whole length.
[5, 1, 2, 3, 4]and[2, 3, 4, 5, 1]both return 1. - Comparing with
nums[left]instead ofnums[right]. On a non-rotated array,nums[middle]is bigger thannums[left]although the minimum is on the left. With that comparison,[11, 13, 15, 17]returns 15 instead of 11. - Using
right = middle - 1. It can discard the minimum itself, whenmiddleholds it. - Using
left <= right. Withright = middle, a window of one index would never shrink, and the loop would run forever.
Testing
[3, 4, 5, 1, 2]gives 1.[4, 5, 6, 7, 0, 1, 2]gives 0.[11, 13, 15, 17]gives 11.[2, 1]gives 1.[2, 3, 4, 5, 1]gives 1.[1]gives 1.
