Optimal Python Solution for Search in Rotated Sorted Array (Interview Script)

2025-09-28

The Logic

  • The array is partially sorted, so a normal binary search needs modification.
  • At every step, one half of the array is guaranteed to be sorted.
  • Use that sorted half to decide whether the target lies inside it or not.

Implementation / Diagram

Key Invariant

At least one side of the midpoint is always sorted, even after rotation.

def search(nums, target):
    left, right = 0, len(nums) - 1

    while left <= right:
        mid = (left + right) // 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 -1