← Problem setPython
#33MediumBinary search
Search in Rotated Sorted Array
The tell: Search a rotated sorted array in logarithmic time.
How you get there
- 1At any midpoint, at least one half is properly sorted.
- 2Determine which half is sorted by comparing nums[lo] to nums[mid].
- 3If the target lies inside that sorted half's range, search it; otherwise search the other.
Solution
def search(nums: list[int], target: int) -> int:
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 is sorted
if nums[lo] <= target < nums[mid]:
hi = mid - 1
else:
lo = mid + 1
else: # right half is sorted
if nums[mid] < target <= nums[hi]:
lo = mid + 1
else:
hi = mid - 1
return -1- Time
- O(log n)
- Space
- O(1)
What goes wrong
Using < instead of <= when testing nums[lo] <= nums[mid] mishandles the two-element case.