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. For example, [0,1,2,4,5,6,7] rotated at k = 3 becomes [4,5,6,7,0,1,2]. The method search receives the rotated array and an integer target, and returns the index of target, or -1 when it isn't there. The rotation point is not given.
In Array(4, 5, 6, 7, 0, 1, 2), the target 0 is at index 4, and the target 3 isn't present, so the answers are 4 and -1. In Array(6, 7, 1, 2, 3, 4, 5) the target 7 is at index 1.
Approach: binary search that finds the sorted half
A loop over every element finds the target in O(n). The lesson asks for O(log n), which means binary search, even though the array as a whole is not sorted.
The key idea: wherever the rotation point is, at least one of the two halves around the middle index is sorted. The values drop only once, at the rotation point, so the drop is in at most one half, and the other half rises from end to end. In a sorted half, comparing the target with the half's two ends tells for certain whether the target can be inside. So each step does the following:
- Check the middle element.
- Work out which half is sorted.
- If the target lies within that sorted half, keep it; otherwise keep the other half.
Each step discards half of the remaining window, giving about log2(n) steps. On Array(4, 5, 6, 7, 0, 1, 2) with the target 0, the window moves like this:
left=0 right=6 middle=3 nums(middle)=7
left=4 right=6 middle=5 nums(middle)=1
left=4 right=4 middle=4 nums(middle)=0
In the first step the left half, 4 5 6 7, is sorted and doesn't contain 0, so the search continues on the right. In the second step the window is 0, 1, 2 and its middle is 1; the left half, 0 and 1, is sorted and contains 0, so the search moves left. The third step finds 0 at index 4.
Step by step
- Set the window.
leftis 0 andrightisnums.length - 1, both inclusive, invars because the loop moves them. - Loop while
left <= right. With<=, a window of one element, whereleftequalsright, still gets checked. - Find the middle:
val middle = left + (right - left) / 2. Integer division already rounds down. Adding half the distance toleftavoids the overflow that(left + right) / 2can cause. - Return
middleifnums(middle) == target. This check comes first, so the later steps only decide which half to drop. - Is the left half sorted? Test
nums(left) <= nums(middle). It uses<=because whenleftequalsmiddle, the left half is one element, and one element is sorted. - If so, is the target in it? Check
nums(left) <= target && target < nums(middle). When true, drop the right half withright = middle - 1. The comparison withnums(middle)is strict because the middle element was already checked. - Otherwise drop the left half:
left = middle + 1. The target can only be in the right part, which may not be sorted, but it is the only place left. - If the left half isn't sorted, the right half is. The rotation point is in the left half, so everything from
middletorightrises. - Is the target in the sorted right half? Check
nums(middle) < target && target <= nums(right). When true, drop the left half withleft = middle + 1. - Otherwise drop the right half:
right = middle - 1. - After the loop, return -1. The window is empty, so every index that could hold the target was ruled out.
The solution in Scala
class Solution {
def search(nums: Array[Int], target: Int): Int = {
var left = 0
var right = nums.length - 1
while (left <= right) {
val middle = left + (right - left) / 2
if (nums(middle) == target) {
return middle
}
if (nums(left) <= nums(middle)) {
if (nums(left) <= target && target < nums(middle)) {
right = middle - 1
} else {
left = middle + 1
}
} else {
if (nums(middle) < target && target <= nums(right)) {
left = middle + 1
} else {
right = middle - 1
}
}
}
return -1
}
}
Scala details worth knowing:
returnexits the method. Scala normally uses the last expression of a block as its value, andreturnis rare. Here it is useful for leaving the loop early when the target is found. Inside a plainwhile, it simply ends the method.- Integer division.
(right - left) / 2on twoInts truncates, somiddleis the lower of two middle indices for an even-sized window. Intoverflow wraps silently. Withleft = 1500000000andright = 2100000000,(left + right) / 2evaluates to-347483648, whileleft + (right - left) / 2gives1800000000. The lesson's arrays have far fewer elements than that, but the safe form costs nothing.varversusval.leftandrightchange, so they arevar.middleis recomputed in every pass as a freshval.- Indexing with parentheses.
nums(middle)reads an element of theArray[Int]. &&short-circuits. Innums(left) <= target && target < nums(middle)both parts must hold, and the second is skipped if the first is false.
Complexity
Time: O(log n). Every pass of the loop either returns or removes at least half of the window, including middle itself. After about log2(n) passes the window is empty.
Space: O(1). The method keeps only left, right and middle.
Edge cases and common mistakes
- A single element.
Array(1)with target 1 returns 0, and with target 0 returns -1. The windowleft = right = 0is checked because the loop condition is<=. - Two elements. In
Array(3, 1)the middle is index 0, soleftequalsmiddle. The testnums(left) <= nums(middle)is true, the left half is one sorted element, and the target 1 falls through toleft = middle + 1. The result is 1. - An array that wasn't rotated.
Array(1, 2, 3, 4, 5)with target 4 returns 3. The left half is always sorted, and it works as an ordinary binary search. - Target at an end of the window. For
Array(4, 5, 6, 7, 0, 1, 2), the target 4 gives 0 and the target 2 gives 6. - Using
<in the loop condition. Withleft < right, a window of one element is never checked, andArray(1)with target 1 returns -1 instead of 0. - Using
<for the sorted-left test. Withnums(left) < nums(middle), a window whereleftequalsmiddleis treated as unsorted on the left. ForArray(3, 1)and target 1, that sends the search the wrong way and the result is -1 instead of 1. - Duplicates. The method relies on distinct values. With repeats,
nums(left) <= nums(middle)can't tell which half is sorted.
Testing
Array(4, 5, 6, 7, 0, 1, 2)with target 0 gives 4.Array(4, 5, 6, 7, 0, 1, 2)with target 3 gives -1.Array(6, 7, 1, 2, 3, 4, 5)with target 7 gives 1.Array(1)with target 1 gives 0, and with target 0 gives -1.Array(3, 1)with target 1 gives 1.Array(1, 3)with target 3 gives 1.Array(1, 2, 3, 4, 5)with target 4 gives 3.
