Search in Rotated Sorted Array
Difficulty: Medium · Pattern: Binary Search · LeetCode #33
A sorted array of distinct integers was rotated at an unknown pivot. Return the index of target, or −1, in O(log n).
Examples
text
nums = [15, 18, 22, 3, 7, 10], target = 7 → 4
nums = [15, 18, 22, 3, 7, 10], target = 16 → −1
nums = [1], target = 1 → 0Hints
- At any
mid, at least one of[lo, mid]or[mid, hi]is sorted normally. - Check whether the target falls inside the sorted half's range; if so, search there, else search the other half.
Approach
At each step, decide which half is sorted:
- If
nums[lo] ≤ nums[mid], the left half is sorted. Ifnums[lo] ≤ target < nums[mid], go left; otherwise go right. - Else the right half is sorted. If
nums[mid] < target ≤ nums[hi], go right; otherwise go left.
Still halving each time: O(log n).
Complexity
Time: O(log n). Space: O(1).
Python solution
def search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # left half sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1JavaScript solution
function search(nums, target) {
let lo = 0, hi = nums.length - 1;
while (lo <= hi) {
const mid = (lo + hi) >> 1;
if (nums[mid] === target) return mid;
if (nums[lo] <= nums[mid]) {
if (nums[lo] <= target && target < nums[mid]) hi = mid - 1; else lo = mid + 1;
} else {
if (nums[mid] < target && target <= nums[hi]) lo = mid + 1; else hi = mid - 1;
}
}
return -1;
}