Problem overview
The method search(nums, target) receives an array of distinct integers that 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]. The method returns the index of target in the rotated array, or -1 when it isn't there. The statement asks for O(log n) time and O(1) extra space.
For [4, 5, 6, 7, 0, 1, 2] and target 0 the answer is 4. For target 3 it is -1. For [6, 7, 1, 2, 3, 4, 5] and target 7 the answer is 1.
Approach: binary search, one sorted half at a time
A linear scan finds the target in O(n), which is too slow for the requested budget. Ordinary binary search needs a fully sorted array, and a rotated one is not. But it is sorted in two pieces, and that is enough.
The key observation: whichever index middle you pick, at least one of the two halves around it is sorted. The values drop only once, at the rotation point, and that drop lies in at most one of the halves. The other half rises from end to end.
So each pass of the loop does this:
- Check
nums[middle]against the target and return if it matches. - Find a sorted half: if
nums[left] <= nums[middle], the left half is sorted; otherwise the right half is. - In a sorted half, two comparisons with its ends tell whether the target can be inside. If it can, keep that half. If not, the target can only be in the other half, so keep that one.
Every pass discards 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]. The first middle is index 3, holding 2. The left value 6 is larger than 2, so the left half is not sorted and the right half, 2 to 5, is. The target 7 is not between 2 and 5, so the search moves left with right = 2. The next middle is index 1, which holds 7, and the function returns 1.
The unsuccessful search for 3 in [4, 5, 6, 7, 0, 1, 2] goes through the windows 0 to 6, then 4 to 6, then 6 to 6, and returns -1 once the window is empty.
Step by step
- Declare
leftandrightwith onelet: the first index, 0, and the last one,nums.length - 1. Both ends are inclusive. - Loop while
left <= right. When they are equal, one element is still to check. - Compute
middleasleft + (right - left) / 2, wrapped inMath.floorbecause the division can produce a fraction and an index must be whole. - Return
middleifnums[middle]equalstarget. After this check, the rest only decides which half to drop. - Test whether the left half is sorted with
nums[left] <= nums[middle]. The<=matters: whenleftequalsmiddle, that half is one element, and one element is sorted. - Left half sorted: the target is inside it when
nums[left] <= targetandtarget < nums[middle]. Then drop the right half withright = middle - 1. - Otherwise drop the left half with
left = middle + 1. - Left half not sorted: then the right half, from
middletoright, is. - Right half sorted: the target is inside it when
nums[middle] < targetandtarget <= nums[right]. Then drop the left half withleft = middle + 1. - Otherwise drop the right half with
right = middle - 1. - After the loop, return
-1: every index that could hold the target has been ruled out.
The solution in JavaScript
class Solution {
search(nums, target) {
let left = 0, right = nums.length - 1;
while (left <= right) {
let middle = Math.floor(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;
}
}
Some JavaScript details worth knowing:
- Division gives a fraction. In JavaScript,
7 / 2is3.5, not 3, andnums[3.5]isundefined.Math.floorturns the offset into a whole number. When the midpoint is computed asleft + (right - left) / 2, it is always betweenleftandright. - No integer overflow to worry about. JavaScript numbers are doubles, so
left + rightwould be exact for any array length here. Writingleft + (right - left) / 2is still a common habit, and it works the same everywhere. ==in the match test. The reference compares with==, which converts types when they differ, so atargetof'0'would match the number 0. With two numbers,==and===give the same answer. The range tests with<=and<also convert strings to numbers. Prefer===in your own code.- Comparison operators on numbers. The comparisons
nums[left] <= targetandtarget < nums[middle]are ordinary numeric comparisons, which work for negative values too.
Complexity
Time: O(log n). Each pass of the loop discards at least half of the window, and every pass does a constant number of comparisons. An array of a million elements needs about 20 passes.
Space: O(1). The function keeps three indices and no extra arrays.
Edge cases and common mistakes
- A single element.
[1]with target 1 gives 0, and with target 0 gives -1. - Two elements. Here
leftequalsmiddle, so the left "half" is one element.[3, 1]with target 1 returns 1. If the sorted-half test used<instead of<=, the same input would return -1, because the code would wrongly treat the left half as unsorted. - No rotation. With
k = 0the array is plain sorted, and the same code works:[0, 1, 2, 4, 5, 6, 7]with target 5 gives 4. - Target at the first or last position.
[5, 1, 3]with target 5 gives 0, and[2, 3, 4, 5, 1]with target 1 gives 4. - A target that is not there. Both ends of the sorted half are compared, so a value outside the array's range, or one that falls in the gap, ends with
leftpastrightand returns -1. - Making the comparisons strict at the wrong end.
nums[middle]was already checked, so it is excluded from the range tests (target < nums[middle]andnums[middle] < target), while the endsnums[left]andnums[right]are included. - Using
< rightin the loop. The condition must beleft <= right, otherwise a window with one element is never examined. - Assuming distinct values. The statement guarantees them. With duplicates,
nums[left] <= nums[middle]can no longer tell which half is sorted, and this approach would need changes.
Testing
nums = [4, 5, 6, 7, 0, 1, 2],target = 0gives4.nums = [4, 5, 6, 7, 0, 1, 2],target = 3gives-1.nums = [6, 7, 1, 2, 3, 4, 5],target = 7gives1.nums = [1],target = 0gives-1.nums = [3, 1],target = 1gives1.nums = [-5, -3, 0, 9, -9, -7],target = -9gives4.
