Problem overview
The function findMin receives an IntArray named nums of distinct integers that were sorted in ascending order and then possibly rotated: the first k elements were moved, in the same order, to the end. For example, [0, 1, 2, 4, 5, 6, 7] rotated with k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. With k = 0 the array stays as it was. The function returns the smallest element, in 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
Scanning the whole array finds the minimum in O(n), and that is a fine first answer, but it ignores the order the array still has. The array rises, drops once at the rotation point, and rises again. The minimum sits right after the drop, or at index 0 when there is no rotation.
Binary search can find that point. Compare the middle element with the last element of the window:
- If
nums[middle] > nums[right], the values must drop somewhere aftermiddle, because in a sorted stretch every value is smaller than the last one. The minimum is to the right ofmiddle, andmiddleitself can't be it, since a bigger value exists after it. - Otherwise
nums[middle]is smaller thannums[right], so everything frommiddletorightis sorted. The minimum is atmiddleor to its left.
Each pass drops about half of the window while keeping the minimum inside it, so the search needs O(log n) passes.
Step by step
- Set the window.
var left = 0andvar right = nums.size - 1. The minimum can be anywhere, so the window starts as the whole array. They arevars because the loop moves them. - Loop
while (left < right). This is<, not<=: the loop stops when the window is one index wide, and that index holds the minimum. - Find the middle:
val middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance toleftcan't overflow, unlike halving the sum. - Drop the left side. If
nums[middle] > nums[right], setleft = middle + 1. - Keep the middle. Otherwise set
right = middle, notmiddle - 1:nums[middle]may be the minimum itself. - Return
nums[left]. Every pass kept the minimum inside the window, and now the window is a single index.
Here are the passes 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
answer index 4
In the first pass, 7 is larger than 2, so the minimum is to the right and left jumps to 4. In the second, 1 is smaller than 2, so right moves to middle. In the third, 0 is smaller than 1, right becomes 4, and the window is one index wide.
On the unrotated [11, 13, 15, 17] the comparison never finds a drop, so right keeps moving left until the window sits at index 0:
left=0 right=3 middle=1 nums[middle]=13 nums[right]=17
left=0 right=1 middle=0 nums[middle]=11 nums[right]=13
answer index 0
The solution in Kotlin
class Solution {
fun findMin(nums: IntArray): Int {
var left = 0
var right = nums.size - 1
while (left < right) {
val middle = left + (right - left) / 2
if (nums[middle] > nums[right]) {
left = middle + 1
} else {
right = middle
}
}
return nums[left]
}
}
Kotlin details worth knowing:
- Integer division.
/on twoIntvalues truncates toward zero. Hereright - leftis never negative, so it rounds down, andmiddleis always belowrightwhileleft < right. That guaranteesright = middleshrinks the window. - Overflow.
Intis 32 bits and wraps silently, so(left + right) / 2can go negative for indices near 2 billion. The formleft + (right - left) / 2is safe. The lesson's arrays are smaller, but the habit costs nothing. varfor moving bounds.leftandrightchange in every pass, so they arevar;middleis new in each pass, so it is avaldeclared inside the loop.- No empty case. The constraints guarantee at least one element. For an empty
IntArray,nums.size - 1is-1, the loop doesn't run, andnums[0]throws anArrayIndexOutOfBoundsException.
Complexity
Time is O(log n): the window loses about half of its indices in each pass. Extra space is O(1): three integers.
Edge cases and common mistakes
- Comparing with
nums[left]instead ofnums[right]. In an array that wasn't rotated,nums[middle]is bigger thannums[left], yet the minimum is on the left. A version that compares withnums[left]and movesleftpastmiddlereturns 15 for[11, 13, 15, 17], instead of 11. - Setting
right = middle - 1. Whennums[middle]is the minimum, this throws it away. - Using
<=in the loop condition. Withright = middle, a window of one index would never shrink, and the loop would not end. - A single element.
[7]gives 7: the loop doesn't run, andnums[0]is returned. - Two elements.
[2, 1]gives 1 and[1, 2]gives 1. - Rotation by one in either direction.
[2, 3, 4, 5, 1]and[5, 1, 2, 3, 4]both give 1. - Distinct values. The solution relies on all values being different: with equal values,
nums[middle]equal tonums[right]would not show where the drop is.
Testing
Results the solution returns:
[3, 4, 5, 1, 2] -> 1
[4, 5, 6, 7, 0, 1, 2] -> 0
[11, 13, 15, 17] -> 11
[7] -> 7
[2, 1] -> 1
[1, 2] -> 1
[2, 3, 4, 5, 1] -> 1
[5, 1, 2, 3, 4] -> 1
