Problem overview
The method Search receives an int[] called nums and an integer target. The array holds distinct values that were 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, or -1 if it is not there. It must run in O(log n) time with O(1) extra space.
In {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: binary search that finds the sorted half
A linear scan is O(n). Plain binary search is O(log n) but needs a fully sorted array. A rotated array is not sorted, but it is two sorted runs glued together, and that is enough.
The key fact: pick any middle index. The values drop only once in the whole array, at the rotation point, so that drop lies in at most one of the two halves around the middle. The other half rises from end to end, so it is sorted. In a sorted range, comparing target with the two ends tells whether it can be inside. That gives a rule for each pass:
- If
nums[middle]is the target, returnmiddle. - Find which half is sorted by comparing
nums[left]withnums[middle]. - If the target lies within the sorted half's range, keep that half. Otherwise keep the other half.
Each pass discards half of the window, so the loop runs about log2 n times.
Take {4, 5, 6, 7, 0, 1, 2} and target 0. The first window is indices 0 to 6, with middle = 3 (value 7). The left half 4, 5, 6, 7 is sorted and 0 is not between 4 and 7, so left becomes 4. The window is now indices 4 to 6, with middle = 5 (value 1). The left half 0, 1 is sorted, and 0 is between 0 and 1, so right becomes 4. The window is the single index 4, with middle = 4, and its value is 0: return 4.
The same idea works whether or not the array was actually rotated. With k = 0 the left half is always the sorted one, and the method behaves like an ordinary binary search.
Step by step
- Declare
left = 0andright = nums.Length - 1. Both ends are inclusive. - Loop while
left <= right. Use<=: when the two are equal, one element is still unchecked. - Compute
middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance toleft, rather than halvingleft + right, can't overflow. - Return
middleifnums[middle] == target. After this check, the later steps only decide which half to drop. - Test
nums[left] <= nums[middle]. If true, the left half is sorted. The<=matters: whenleft == middle, the half is one element, which is sorted. - Left half sorted: if
nums[left] <= target && target < nums[middle], setright = middle - 1. The comparison withnums[middle]is strict, because that element was already checked. - Otherwise set
left = middle + 1: the target can only be in the other half. - Left half not sorted: then the right half, from
middletoright, is. Ifnums[middle] < target && target <= nums[right], setleft = middle + 1. - Otherwise set
right = middle - 1. - After the loop, the window is empty: return
-1.
The solution in C#
class Solution {
public int Search(int[] nums, int target) {
int left = 0, right = nums.Length - 1;
while (left <= right) {
int 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;
}
}
C# details worth knowing:
- Integer division truncates.
(right - left) / 2on twointvalues discards the fraction, somiddleis the lower of the two central indices when the window has an even length. - Overflow wraps silently.
intarithmetic is unchecked by default. For arrays of up to a million elements(left + right) / 2is fine, but theleft + (right - left) / 2form stays correct for any array length. - Several variables in one declaration.
int left = 0, right = nums.Length - 1;declares twoints, each with its own initial value. - No exception on a miss. The method returns
-1as a result value, a convention likeArray.IndexOf, instead of throwing.
Complexity
Time: O(log n). Every pass either returns or halves the window, so there are at most about log2 n passes.
Space: O(1). Only left, right and middle are kept.
Edge cases and common mistakes
- Not rotated. With
k = 0the array is plain sorted, and the left half is always the sorted one.Search(new[] {0, 1, 2, 4, 5, 6, 7}, 5)returns 4. - One element.
{1}with target 1 returns 0, and with target 0 returns -1. - Two elements.
{1, 3}with target 3 returns 1. Heremiddleequalsleft, which is whynums[left] <= nums[middle]must use<=. - Target at the rotation point. For
{6, 7, 1, 2, 3, 4, 5}and target 7, the answer is 1. - Target absent.
{4, 5, 6, 7, 0, 1, 2}with target 3 returns -1. - Using
<in the sorted-half test. A single-element half is then taken for an unsorted one, and the search goes to the wrong side. - Looping with
left < right. The last remaining element would never be checked.
Testing
{4, 5, 6, 7, 0, 1, 2}with target 0 gives4.{4, 5, 6, 7, 0, 1, 2}with target 3 gives-1.{6, 7, 1, 2, 3, 4, 5}with target 7 gives1.{1}with target 0 gives-1.{1, 3}with target 3 gives1.
