Find a target in a sorted array that was rotated once.
Start with the concrete trace below. It shows the state the algorithm must carry as it runs.
Problem trace
Search in Rotated Sorted Array: Keep the interval containing target 0 by identifying one sorted half at each probe.
- Recognize it
- The array was sorted and rotated once with distinct values, so although the whole interval may cross the pivot, at least one side of middle remains sorted.
- Keep true
- If target 0 exists, it remains in inclusive [left, right]. A half is discarded only after its sorted value range proves whether target can occur there.
- Reuse it
- When a monotone ordering is disrupted once, find a locally ordered region and use its endpoint values to make the same safe-elimination argument as ordinary binary search.
Pattern: Binary search with one sorted half.
Simple idea: At least one half around the middle is sorted. Find that half. If the target fits inside its values, search it. Otherwise search the other half.
def search_rotated(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
middle = (left + right) // 2
if nums[middle] == target:
return middle
if nums[left] <= nums[middle]:
if nums[left] <= target < nums[middle]:
right = middle - 1
else:
left = middle + 1
elif nums[middle] < target <= nums[right]:
left = middle + 1
else:
right = middle - 1
return -1
Cost: time and space.