Search in Rotated Sorted Array
Find a target in a rotated sorted array in O(log n) by checking which half around the middle is sorted.
The problem
You get an array nums of distinct integers that was sorted in increasing order and then possibly rotated, so that some elements from the end moved to the front in order. Given an integer target, return its index in nums, or -1 if it is not there. Your solution must run in O(log n) time.
Input nums = [12, 15, 19, 3, 6, 8], target = 6
Output 4
6 sits at index 4, in the part after the break.
Input nums = [7, 9, 1, 4], target = 8
Output -1
8 is not in the array.
How to spot the pattern
- The array is sorted except for one break point, and O(log n) is required.
- At any middle point at least one of the two halves is fully sorted, and you can check whether the target falls inside it.
The idea
Cut the range at mid: one of the two halves is always in sorted order, and comparing nums[lo] with nums[mid] tells you which. For the sorted half, a quick range check says whether target can be inside it; if it can, search there, and if not, search the other half. Each step still halves the range, so the search stays O(log n).
Brute force: Scan the array for the target, which takes O(n) time.
Step by step
- 1Set
lo = 0andhi = n - 1, and loop whilelo <= hi. - 2Compute
mid; ifnums[mid]equalstarget, returnmid. - 3If
nums[lo] <= nums[mid], the left half is sorted: go left ifnums[lo] <= target < nums[mid], otherwise go right. - 4Otherwise the right half is sorted: go right if
nums[mid] < target <= nums[hi], otherwise go left. - 5If the loop ends, return -1.
See the pattern move
The binary search pattern on a small example. Step through it, or press play.
Code
class Solution:
def search(self, nums: List[int], target: int) -> int:
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2
if nums[mid] == target:
return mid
if nums[lo] <= nums[mid]: # the left half is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # the right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1Complexity
Time
O(log n)
Space
O(1)
One binary search; each step does a few comparisons and halves the range.
Watch out for
- Testing
nums[lo] < nums[mid]instead of<=: whenlo == midthe one-element left half counts as sorted, and the strict check sends [3, 1] with target 1 the wrong way. - Getting the range checks wrong at the edges: the target can equal
nums[lo]ornums[hi], so those comparisons need<=.
Follow-up questions
What if the array can contain duplicates?
When nums[lo], nums[mid] and nums[hi] are all equal you can't tell which half is sorted, so move both ends inward by one and continue. The worst case becomes O(n); that is Search in Rotated Sorted Array II.
Can you solve it with two simpler binary searches?
Yes: first find the index of the minimum (Find Minimum in Rotated Sorted Array), then run a plain binary search on whichever sorted run could hold the target.
In Hinglish
Har baar dekho kaunsa half sorted hai; target us half ki range mein hai toh wahan jao, warna doosre half mein.