Problem overview
The method search receives nums, an array of distinct integers that was sorted in ascending order and then possibly rotated, and a number target. A rotation at index k moves the first k elements, in the same order, to the end: [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 nums, or -1 if it is not there. It must run in O(log n) time with O(1) extra space.
For nums = [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is missing, so the answer is -1.
Approach: one half is always sorted
A linear scan is O(n). Ordinary binary search is O(log n) but needs a sorted array, and a rotated one is only sorted in two pieces. The lesson's key idea is that, whatever 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 in at most one half, and the other half rises from end to end.
In a sorted half, comparing target with the half's two ends tells whether it can be inside. So each pass does this:
- Check
middleitself. - Find which half is sorted.
- If
targetlies within that sorted half, keep it. Otherwise keep the other half.
Either way, half the window is dropped, so the loop runs about log2 n times.
Take nums = [6, 7, 1, 2, 3, 4, 5] and target = 7. The first window is indices 0 to 6, and middle is 3, which holds 2. The right half, [2, 3, 4, 5], is sorted and 7 isn't between 2 and 5, so 7 can only be in the left half. The window becomes indices 0 to 2, with middle at 1, which holds 7. The method returns 1.
Step by step
- Set the window with one
let:leftis 0 andrightisnums.length - 1. Both ends are inclusive. - Loop while
left <= right. When they are equal, one element is still to check, so<=is needed. - Compute
middleasMath.floor(left + (right - left) / 2). Division keeps the fraction in JavaScript numbers (7 / 2is 3.5), and an index must be whole. - Return
middleif it holds the target. This check comes first, so the later steps only decide which half to drop. - Test whether the left half is sorted:
nums[left] <= nums[middle]. The<=matters: whenleftequalsmiddle, the half is a single element, which counts as sorted. - If the left half is sorted and
targetis in it (at leastnums[left]and strictly less thannums[middle]), moverighttomiddle - 1. - 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. - If
targetis in the sorted right half (strictly greater thannums[middle]and at mostnums[right]), movelefttomiddle + 1. - Otherwise move
righttomiddle - 1. - After the loop, return -1. Every index that could hold the target has been ruled out.
The solution in TypeScript
class Solution {
search(nums: number[], target: number): number {
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 TypeScript details:
Math.flooris required. In TypeScript,numberis a double and/never truncates, so(0 + 6) / 2is fine but(0 + 7) / 2is 3.5. An index of 3.5 readsundefinedfrom the array instead of failing.- No overflow worry.
left + (right - left) / 2is the form that avoids overflow in languages with 32-bit integers. TypeScript numbers don't overflow at these sizes, but the form is still correct. ==here. The reference uses==fornums[middle] == target. With two numbers it behaves like===, which is the form most code prefers because it never converts types.- Window state in two variables. The method uses only
left,rightandmiddle, which is why the space is constant.
Complexity
Time: O(log n). Each pass of the loop drops at least half of the window, so at most about log2 n passes happen, with constant work in each.
Space: O(1). Only a few numbers are stored.
Edge cases and common mistakes
- Strict
<when testing the sorted half. Withnums[left] < nums[middle], a two-element window such as[3, 1]is treated as having an unsorted left half. Searching for 1 in[3, 1]then returns -1 instead of 1. - Using
<in the loop condition. A window of one element would never be checked, and a one-element array would fail. - Forgetting one end of a range test. The target can equal
nums[left]ornums[right], so those comparisons use<=. The comparison withnums[middle]is strict, becausemiddlewas already checked. - No rotation. With
k = 0the array is plain sorted. The left half is then always sorted, and the method acts as ordinary binary search. For[0, 1, 2, 4, 5, 6, 7]with target 5 it returns 4. - Duplicates. The method relies on distinct values. With repeated values,
nums[left] <= nums[middle]can't tell which half is sorted, and the lesson's constraints exclude that case. - Missing target. It returns -1, as in
[1]with target 0.
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 = [3, 1],target = 1gives1.nums = [5, 1, 3],target = 5gives0.nums = [1],target = 0gives-1.
