PracticeNeetCode ↗LeetCode ↗
Given a rotated sorted array of unique integers and a target value, return its index, or -1 if it isn't present. The solution must run in O(log n) time.
left = 0, right = len(nums) - 1.mid; if nums[mid] equals the target, return mid.nums[left] is less than or equal to nums[mid], the left half is sorted: when the target falls within that sorted range, search the left half; otherwise search the right half.Time: O(log n) — Space: O(1)
def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1How the solution above works, piece by piece.
mid, at least one of the two halves is fully sorted.nums[mid] is the target, done.nums[left] <= nums[mid] means the left half is sorted. Check whether the target lies inside its range; if so search there, otherwise search the right half.nums[mid] .. nums[right].Running it on nums = [4, 5, 6, 7, 0, 1, 2], target = 0: