Problem overview
The function search receives an IntArray named nums and an integer target. The array held distinct integers in ascending order, and then it was 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 with k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. The function returns the index of target in the rotated array, or -1 if it isn't there, in O(log n) time and O(1) extra space.
In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is absent, so the result is -1. In [6, 7, 1, 2, 3, 4, 5], the target 7 is at index 1.
Approach
A loop over the array finds the target in O(n), but O(log n) calls for binary search, which needs an order to exploit. A rotated array is not sorted as a whole, so the usual comparison with the middle element doesn't tell which half holds the target.
The key idea is that wherever the rotation point is, at least one of the two halves around middle is sorted. The values drop only once, at the rotation point, so the drop falls inside at most one half, and the other half rises from end to end. The search works in three moves:
- Check whether
nums[middle]is the target. - Find which half is sorted by comparing
nums[left]withnums[middle]. - In a sorted half, two comparisons with its ends tell whether the target can be inside. If it can, keep that half. If not, keep the other one.
Each pass drops half of the window, so the loop runs about log2 n times.
Step by step
- Set the window.
var left = 0andvar right = nums.size - 1. Both ends are inclusive, so the window is everything fromlefttoright. They arevars because the loop moves them. - Loop
while (left <= right). With<=, a window of one element is still checked. - Find the middle:
val middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance toleftnever overflows, unlike halving the sum. - Check for a hit: if
nums[middle] == target, returnmiddle. This comes first, so the steps below only decide which half to drop. - Is the left half sorted? Test
nums[left] <= nums[middle]. Use<=: whenleftequalsmiddle, the left half is a single element, and one element is sorted. - Target in the sorted left half? If
nums[left] <= target && target < nums[middle], setright = middle - 1. The comparison withnums[middle]is strict, because that element was already checked. - Otherwise the target can't be in the sorted left half: set
left = middle + 1. - The else branch of the sorted-left test handles the case where the left half isn't sorted. Then the rotation point is in the left half, so everything from
middletorightrises. - Target in the sorted right half? If
nums[middle] < target && target <= nums[right], setleft = middle + 1. This is the same test, mirrored. - Otherwise set
right = middle - 1. - After the loop the window is empty and every possible index has been ruled out, so return
-1.
Here is the search for 7 in [6, 7, 1, 2, 3, 4, 5], printing the window on each pass:
left=0 right=6 middle=3 nums[middle]=2
left=0 right=2 middle=1 nums[middle]=7
found at 1
At the first pass, nums[0] = 6 is larger than nums[3] = 2, so the left half isn't sorted and the right half, 2 to 5, is. The target 7 is not between 2 and 5, so the search moves left. The second pass finds it. For the target 0 in [4, 5, 6, 7, 0, 1, 2], the passes show middle as 3, then 5, then 4, and the target is found at index 4.
The solution in Kotlin
class Solution {
fun search(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size - 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
}
}
Kotlin details worth knowing:
- Integer division.
/on twoIntvalues truncates, so(right - left) / 2is a whole number. - Overflow.
Intis 32 bits and wraps silently. Withleft = 2000000000andright = 2100000000, the expression(left + right) / 2gives-97483648, whileleft + (right - left) / 2gives2050000000. The lesson's arrays are far smaller than that, but the safe form costs nothing. - Early
return. Areturninside thewhileloop leaves the function at once, so the finalreturn -1runs only when the loop ends without a hit. - Short-circuit
&&. Each range test is a pair of comparisons joined by&&, and both must hold for the target to be inside the sorted half.
Complexity
Time is O(log n): every pass of the loop halves the window. Extra space is O(1): three integers and no copies of the array.
Edge cases and common mistakes
- Using
<innums[left] <= nums[middle]. With two elements,leftequalsmiddle, and the left half is one sorted element. With<the code treats it as unsorted. For[3, 1]and target 1, the solution returns1, but a version with the strict comparison returns-1. - A single element.
[1]with target 1 gives0, and with target 0 gives-1. - Not rotated. With
k = 0the array is plain sorted.[1, 2, 3, 4, 5]with target 5 gives4: the left half is always sorted, so this is ordinary binary search. - Rotation by one.
[5, 1, 2, 3, 4]with target 5 gives0, and[2, 3, 4, 5, 1]with target 1 gives4. Both ends of the array can hold the target. - Moving a pointer to
middleinstead of past it. After the hit check,middleis known not to be the target, so the code always moves tomiddle - 1ormiddle + 1. Keepingmiddlein the window could loop forever. - Distinct values. The solution relies on all values being different. With duplicates,
nums[left] == nums[middle]can't tell which half is sorted.
Testing
Results the solution returns:
[4, 5, 6, 7, 0, 1, 2], target 0 -> 4
[4, 5, 6, 7, 0, 1, 2], target 3 -> -1
[6, 7, 1, 2, 3, 4, 5], target 7 -> 1
[1], target 1 -> 0
[1], target 0 -> -1
[3, 1], target 1 -> 1
[1, 2, 3, 4, 5], target 5 -> 4
[5, 1, 2, 3, 4], target 5 -> 0
[2, 3, 4, 5, 1], target 1 -> 4
