Search in Rotated Sorted Array

Search for a target in a rotated sorted array.

Pattern

Modified Binary Search

This problem follows the Modified Binary Search pattern, commonly found in the Binary Search category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Determine which half is sorted. Check if target is in the sorted half.

Key Insight

At least one half is always sorted in a rotated array — determine which half is sorted, then check if the target is in that range.

Step-by-step

  1. 1Set left = 0, right = len(nums) - 1
  2. 2Determine which half is sorted by comparing nums[left] with nums[mid]
  3. 3Check if target falls within the sorted half's range
  4. 4If yes, search that half; otherwise, search the other half

Pseudocode

left, right = 0, len(nums) - 1
while left <= right:
    mid = (left + right) // 2
    if nums[mid] == target: return mid
    if nums[left] <= nums[mid]:  # left half sorted
        if nums[left] <= target < nums[mid]:
            right = mid - 1
        else:
            left = mid + 1
    else:  # right half sorted
        if nums[mid] < target <= nums[right]:
            left = mid + 1
        else:
            right = mid - 1
return -1
Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(1)
More Binary Search Problems

Master this pattern with YeetCode

Practice Search in Rotated Sorted Array and similar Binary Search problems with flashcards. Build pattern recognition through active recall.

Practice this problem