Problem overview
The method search 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. Given nums after the rotation and a target, it returns the index of target, or -1 if it isn't there. The statement asks for O(log n) time and O(1) extra space.
For nums = [4, 5, 6, 7, 0, 1, 2] and target = 0, the answer is 4. For target = 3, the answer is -1.
Approach: find a sorted half, then decide
A loop that checks every element finds the target in O(n), which is too slow for the target complexity. Plain binary search needs a sorted array, and a rotated array isn't sorted: its values rise, drop once at the rotation point, and rise again.
The lesson's 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, so the drop lies in at most one half, and the other half rises from end to end. A sorted half can be tested with its two ends: target is inside it exactly when it lies between them. If it is, search there. If not, it can only be in the other half. Every pass drops half of the window, which gives O(log n).
Here is the search for 0 in [4, 5, 6, 7, 0, 1, 2]:
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
found 4
In the first pass, nums[left] is 4 and nums[middle] is 7, so the left half [4, 5, 6, 7] is sorted. The target 0 isn't between 4 and 7, so the left half is dropped. The second pass has nums[left] = 0 and nums[middle] = 1: the left half is sorted, 0 is at least nums[left] and less than 1, so the search moves left and finds it at index 4.
Step by step
- Set up the window.
leftandrightstart at 0 andnums.count - 1, both inclusive, so the window is everything fromlefttoright. - Loop while
left <= right. Use<=: when they are equal, one element is still left to check. - Compute
middleasleft + (right - left) / 2. Integer division already rounds down, and adding half the distance toleftnever overflows, unlike halving the sum. - Check for the target. If
nums[middle]equalstarget, returnmiddle. After this check, the steps only decide which half to drop. - Find the sorted half. If
nums[left] <= nums[middle], the left half is sorted. The<=matters: whenleftequalsmiddle, the left half is a single element, and one element is sorted. - Target in the sorted left half? If
nums[left] <= targetandtarget < nums[middle], setright = middle - 1. The comparison withnums[middle]is strict, because that element was already checked. - Otherwise it can't be in the left half, so set
left = middle + 1. - If the left half isn't sorted, the right half, from
middletoright, is. - Target in the sorted right half? If
nums[middle] < targetandtarget <= nums[right], setleft = middle + 1. - Otherwise set
right = middle - 1. - Return -1 after the loop: the window is empty, and every index that could hold the target has been ruled out.
The solution in Swift
class Solution {
func search(_ nums: [Int], _ target: Int) -> Int {
var left = 0, right = nums.count - 1
while left <= right {
let 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
}
}
Swift details worth knowing:
- Two variables in one line.
var left = 0, right = nums.count - 1declares twoIntvariables. They arevarbecause the loop moves them. middleis alet. It is computed fresh in every pass of the loop, so a constant is enough.- No optional result. The method returns a plain
Int, with -1 meaning "not found", the way the lesson asks. - Integer division truncates toward zero. Here
right - leftis never negative inside the loop, so/ 2rounds down. - Overflow would stop the program. In Swift, arithmetic overflow traps. With a 64-bit
Intand arrays of at most a million elements, neither form of the midpoint overflows, butleft + (right - left) / 2is the habit that stays safe.
Complexity
Time: O(log n). Each pass of the loop either returns or discards at least half of the window, so there are at most about log base 2 of n passes.
Space: O(1). The method uses only left, right and middle.
Edge cases and common mistakes
- One element.
[1]with target 1 returns 0, and with target 0 returns -1. - Two elements.
[3, 1]with target 1 returns 1. Heremiddleequalsleft, so the left half is a single element and counts as sorted. That is why the test uses<=. - No rotation.
[0, 1, 2, 4, 5, 6, 7]with target 6 returns 5. The left half is sorted in every pass, and the method behaves like ordinary binary search. - Target at an end.
[4, 5, 6, 7, 0, 1, 2]with target 4 returns 0, and with target 2 returns 6. The comparisons withnums[left]andnums[right]are inclusive, so the ends of a sorted half count as inside it. - Target not present.
[4, 5, 6, 7, 0, 1, 2]with target 3 returns -1. - Using
left < rightas the loop condition. A window of one element would never be checked, so[1]with target 1 would return -1. - Strict comparisons at the ends. Writing
nums[left] < targetwould miss a target sitting exactly atleft.
Testing
[4, 5, 6, 7, 0, 1, 2]with target 0 gives 4.[4, 5, 6, 7, 0, 1, 2]with target 3 gives -1.[6, 7, 1, 2, 3, 4, 5]with target 7 gives 1.[3, 1]with target 1 gives 1.[5, 1, 3]with target 5 gives 0.[1]with target 0 gives -1.
