Problem overview
The function search receives a slice of distinct integers, nums, and an integer target. The slice was sorted in ascending order and then 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 at k = 3 becomes [4, 5, 6, 7, 0, 1, 2], and with k = 0 it stays as it was. The function returns the index of target in nums, or -1 if it isn't there.
In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 isn't present, so the answer is -1. The budget is O(log n) time and O(1) extra space, which rules out scanning the slice and calls for binary search.
Approach: one half is always sorted
Plain binary search needs a fully sorted slice: compare the middle element with the target and drop the half that can't hold it. A rotated slice isn't sorted, so a single comparison with the middle tells nothing about which side to keep.
But the rotation leaves one useful property. The values drop only once, at the rotation point, so that drop falls in at most one of the two halves around middle. The other half rises from its first element to its last. In a sorted half, comparing the target with the half's two ends is enough to know whether the target can be inside it:
- If the left half, from
lefttomiddle, is sorted, and the target lies betweennums[left]andnums[middle], keep the left half. Otherwise the target can only be in the right half. - If the left half isn't sorted, the right half is. Keep it if the target lies between
nums[middle]andnums[right], and otherwise keep the left.
Every pass drops half of the window, so the loop runs about log₂ n times.
Here is the search for 7 in [6, 7, 1, 2, 3, 4, 5]. At first left is 0 and right is 6, so middle is 3 and nums[3] is 2. The left half starts with 6, which is bigger than 2, so it isn't sorted, and the right half, [2, 3, 4, 5], is. The target 7 isn't between 2 and 5, so the search moves to the left half with right = 2. Now middle is 1 and nums[1] is 7: the function returns 1.
Step by step
- Declare both ends in one statement:
leftis 0 andrightislen(nums) - 1. Both are inclusive, so the window is everything fromlefttoright. - Loop while
left <= right. When they are equal, one element is still left to check. - Compute
middleasleft + (right-left)/2. Integer division rounds down, and adding half the distance toleftavoids the overflow that halving a sum could cause in other languages. - Return
middleifnums[middle] == target. After this check, the steps only have to decide which half to drop. - Test whether the left half is sorted:
nums[left] <= nums[middle]. With<=, a half with a single element, whenleftequalsmiddle, counts as sorted. - In the sorted left half, if
nums[left] <= targetandtarget < nums[middle], moverighttomiddle - 1. The comparison withnums[middle]is strict, because that element was already checked. - Otherwise move
lefttomiddle + 1: the target can't be in the sorted left half. - If the left half isn't sorted, the right half, from
middletoright, is. - In the sorted right half, if
nums[middle] < targetandtarget <= nums[right], movelefttomiddle + 1. - Otherwise move
righttomiddle - 1: the target can only be in the left half. - Return -1 after the loop. The window is empty, and every index that could hold the target was ruled out.
The solution in Go
func search(nums []int, target int) int {
left, right := 0, len(nums)-1
for left <= right {
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
}
The Go details worth a closer look:
- Go's while loop.
for left <= right { ... }is aforwith only a condition. Go has nowhilekeyword. - Multiple declaration.
left, right := 0, len(nums)-1declares both variables on one line. - Integer division.
(right-left)/2on twoints truncates toward zero. The difference is never negative inside the loop, so it rounds down. Becauseintis 64 bits on a 64-bit build, even(left+right)/2would not overflow for a slice of at most 10⁶ elements, but theleft + (right-left)/2form is safe in general. - No parentheses around conditions. Go's
ifdoesn't need them, but the braces are required, even for a one-line body. - Return values. Every path ends in a
return: inside the loop when the target is found, or-1after it. Go refuses to compile a function with a result type if some path can reach the end without returning.
Complexity
Time: O(log n). Every iteration either returns or discards at least half of the window, so at most about log₂ n iterations run, each doing a constant amount of work.
Space: O(1). Only left, right and middle are kept. The slice is not copied or changed.
Edge cases and common mistakes
- One element.
[1]with target 1 gives 0, and with target 0 gives -1. - Not rotated.
[1, 2, 3, 4]with target 4 gives 3. The left half is sorted at every step, and the search behaves like an ordinary binary search. - Two elements.
[3, 1]with target 1 gives 1. Hereleftequalsmiddleat the first step, so the "left half is sorted" test must use<=. With a strict<, the left half would count as unsorted, the code would look for the target in the right half and wrongly return -1. - Looping while
left < right. The last remaining element is then never checked. With[1]and target 1, the loop doesn't run and the function returns -1. - Target at the first element.
[5, 1, 2, 3, 4]with target 5 gives 0. The first test usesnums[left] <= target, with<=, so the left end of the sorted half is included. - Target not present.
[4, 5, 6, 7, 0, 1, 2]with target 3 gives -1, once the window empties. - Duplicates. The lesson guarantees distinct values. With duplicates,
nums[left] <= nums[middle]can't tell a sorted half from a rotated one, and the method would need extra handling.
Testing
nums = [4, 5, 6, 7, 0, 1, 2],target = 0gives 4.nums = [4, 5, 6, 7, 0, 1, 2],target = 3gives -1.nums = [4, 5, 6, 7, 0, 1, 2],target = 7gives 3.nums = [6, 7, 1, 2, 3, 4, 5],target = 7gives 1.nums = [3, 1],target = 1gives 1.nums = [1, 2, 3, 4],target = 4gives 3.nums = [1],target = 0gives -1.
