Problem overview
The array nums holds distinct integers that were sorted in ascending order and then possibly rotated: its first k elements were moved, in order, to the end. The method findMin returns the smallest element of the rotated array. The rotation point is not given, and it may be 0, which means the array wasn't rotated at all.
For Array(3, 4, 5, 1, 2) the answer is 1, and for Array(4, 5, 6, 7, 0, 1, 2) it is 0. For Array(11, 13, 15, 17) the array wasn't rotated, so the minimum is its first element, 11.
Approach: binary search on the drop
Scanning every element finds the minimum in O(n). The lesson asks for O(log n), so it uses binary search. The array isn't sorted, but it has a clear shape: it rises, drops once at the rotation point, and rises again. The minimum is the element right after the drop, or the first element if there is no drop.
At each step, compare the middle element with the last element of the window:
- If
nums(middle)is bigger thannums(right), the values must drop somewhere aftermiddle, so the minimum is to its right. - Otherwise, everything from
middletorightis sorted, so the minimum is atmiddleor somewhere to its left.
The window halves on every pass, so the search takes about log2(n) steps.
Comparing with the right end is deliberate. Comparing with the left end looks natural but breaks on an array that wasn't rotated: there nums(middle) is always bigger than nums(left), yet the minimum is on the left.
Step by step
- Set the window.
leftis 0 andrightisnums.length - 1, both invars because the loop moves them. The minimum can be anywhere, so the window starts as the whole array. - Loop while
left < right. This time the strict comparison is right: the loop stops when the window is a single index, 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 the way(left + right) / 2can. - Middle bigger than the last element: the drop is after
middle, andmiddleitself can't be the minimum because a smaller element exists, soleft = middle + 1. - Otherwise:
nums(middle)is smaller thannums(right). Everything frommiddletorightis sorted, so the minimum is atmiddleor earlier:right = middle. It's notmiddle - 1, becausenums(middle)may be the minimum itself. - Return
nums(left)after the loop, whenleftandrighthave met.
On Array(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
In the first row 7 is bigger than 2, so left jumps to 4. In the second row 1 is smaller than 2, so right moves to 5, and in the third 0 is smaller than 1, so right moves to 4. The window is then one index, and nums(4) is 0.
The solution in Scala
class Solution {
def findMin(nums: Array[Int]): Int = {
var left = 0
var right = nums.length - 1
while (left < right) {
val middle = left + (right - left) / 2
if (nums(middle) > nums(right)) {
left = middle + 1
} else {
right = middle
}
}
return nums(left)
}
}
Scala details worth knowing:
- Arrays are indexed with parentheses.
nums(left)reads an element, and square brackets are for type parameters. returnis optional. The method could end withnums(left)alone, since the last expression of a block is its value. The explicitreturngives the same result.varfor the moving ends.leftandrightare reassigned in the loop.middleis avaldeclared inside the loop, created fresh on every pass.- Integer division truncates. With
left = 4andright = 5,middleis 4, the lower index. That's whyright = middlealways makes progress, whileleft = middle + 1does too. - Overflow.
Intarithmetic wraps silently. Withleft = 1500000000andright = 2100000000,(left + right) / 2gives-347483648, andleft + (right - left) / 2gives1800000000.
Complexity
Time: O(log n). Each pass moves left to middle + 1 or right to middle, and either way the window shrinks to at most half of its size, rounded up. After about log2(n) passes it has one index.
Space: O(1). Only left, right and middle are stored.
Edge cases and common mistakes
- A single element.
Array(7)skips the loop, becauseleftequalsright, and returns 7. - Two elements.
Array(2, 1)returns 1: the middle is index 0, 2 is bigger than 1, andleftbecomes 1.Array(1, 2)returns 1 as well, withrightmoving to 0. - No rotation.
Array(11, 13, 15, 17)returns 11. At every stepnums(middle)is smaller thannums(right), sorightkeeps moving left until it reaches 0. - The minimum at the end.
Array(2, 3, 4, 5, 1)returns 1. - The minimum just after the first element.
Array(5, 1, 2, 3, 4)returns 1. - Comparing with
nums(left). A version that moveslefttomiddle + 1whennums(middle) > nums(left)returns 15 onArray(11, 13, 15, 17)instead of 11. - Setting
right = middle - 1. It can skip the minimum. OnArray(3, 1, 2)the middle is 1, which is smaller than 2, so that version movesrightpast it and returns 3 instead of 1. - Using
left <= right. Withright = middlein theelsebranch, the window can stop shrinking, and the loop would never end.
Testing
Array(3, 4, 5, 1, 2)gives 1.Array(4, 5, 6, 7, 0, 1, 2)gives 0.Array(11, 13, 15, 17)gives 11.Array(7)gives 7.Array(2, 1)gives 1.Array(5, 1, 2, 3, 4)gives 1.Array(2, 3, 4, 5, 1)gives 1.
