Search in Rotated Sorted Array
Adapt binary search to an array with one rotation point.
Try It Yourself
Use the editor below to search a rotated sorted array in logarithmic time. At every step, identify which half is still normally sorted.
Submit your implementation when it passes the examples. Handle one-element arrays, missing values, and targets on either side of the rotation.
Search in Rotated Sorted Array
A strictly increasing array was rotated at an unknown position. Given the rotated array and a target, return the target's index.
Return -1 when the target is absent, using logarithmic time.
Example 1:
Example 2:
Constraints
1 ≤ nums.length ≤ 5,000- All values are distinct.
Solution
At least one half around the middle is sorted. Determine whether the target lies inside that sorted half; if it does, keep that half, and otherwise search the other side.
This decision preserves binary search's ability to discard half of the remaining array after every comparison.
function searchRotated(nums, target) {
let left = 0;
let right = nums.length - 1;
while (left <= right) {
const middle = left + Math.floor((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;
}Big O notation
| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(log n) | A sorted-half check discards half of the remaining array each iteration. |
| Auxiliary space | O(1) | The search stores only three indices. |