Search in Rotated Sorted Array in Python

Consider we have an array sorted in ascending order that is rotated at some unknown pivot. For example, [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]. Given a target value to search, we return its index if found, otherwise return -1. We assume no duplicates exist in the array.

Algorithm

We use a modified binary search approach ?

  • Initialize low = 0 and high = length of array
  • While low < high:
    • Calculate mid = low + (high - low) // 2
    • If arr[mid] == target, return mid
    • If arr[low] <= arr[mid] (left half is sorted):
      • If target >= arr[low] and target < arr[mid], search left: high = mid
      • Otherwise, search right: low = mid + 1
    • Otherwise (right half is sorted):
      • If target <= arr[high-1] and target > arr[mid], search right: low = mid + 1
      • Otherwise, search left: high = mid
  • Return -1 if not found

Example

Let's implement this solution ?

class Solution:
    def search(self, nums, target):
        low = 0
        high = len(nums)
        
        while low < high:
            mid = low + (high - low) // 2
            
            if nums[mid] == target:
                return mid
                
            if nums[low] <= nums[mid]:
                if target >= nums[low] and target < nums[mid]:
                    high = mid
                else:
                    low = mid + 1
            else:
                if target <= nums[high-1] and target > nums[mid]:
                    low = mid + 1
                else:
                    high = mid
        
        return -1

# Test the solution
solution = Solution()
result = solution.search([4, 5, 6, 7, 0, 1, 2], 0)
print(f"Index of target 0: {result}")

# Test with another example
result2 = solution.search([4, 5, 6, 7, 0, 1, 2], 3)
print(f"Index of target 3: {result2}")
Index of target 0: 5
Index of target 3: -1

How It Works

The key insight is that in a rotated sorted array, at least one half is always sorted. We determine which half is sorted and check if our target lies in that sorted range. If yes, we search that half; otherwise, we search the other half.

4 5 6 7 0 1 2 0 1 2 3 4 5 6 Left Half (Sorted) Right Half (Sorted) Target: 0 (Found at index 4) Rotated Sorted Array Search

Time and Space Complexity

The time complexity is O(log n) as we eliminate half of the search space in each iteration. The space complexity is O(1) as we only use a constant amount of extra space.

Conclusion

Searching in a rotated sorted array uses modified binary search by identifying which half is sorted and determining if the target lies in that range. This maintains O(log n) time complexity even with rotation.

Updated on: 2026-03-25T07:45:20+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements