#33
Medium
Binary Search

Search in Rotated Sorted Array

Search for a target in a rotated sorted array.

Search a target in a rotated sorted array in O(log n). The key is recognizing that at least one half remains sorted after every split.

ArrayBinary Search

Pattern fit

At every step one half is still sorted, so binary search becomes a matter of detecting which half is ordered and whether the target belongs there.

Key observation

You are not comparing target with random values; you are using sorted-half structure to eliminate half the array safely.

Target complexity

O(log n) / O(1)

How to break down the solution cleanly

1

Binary search as usual, but first determine which half is sorted.

2

If the left half is sorted, check whether target lies inside that ordered interval.

3

Otherwise the right half must be sorted, so test target against that interval instead.

4

Discard the half that cannot possibly contain target and continue.

Walk through one example

1

Example: nums = [4,5,6,7,0,1,2], target = 0.

2

mid points to 7, and the left half [4,5,6,7] is sorted.

3

Target 0 is not inside that half, so move to the right half.

4

Repeat once more and you land on index 4.

Reference implementation

Python
def search(nums: list[int], target: int) -> int:
    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

Common pitfalls

warning

Failing to distinguish which half is sorted before moving pointers.

warning

Using standard binary-search branches without respecting rotation structure.

Common follow-ups

How does the duplicate-value version change?

What invariant stays true after each branch?

Continue with related problems

Build repeatable depth inside the Binary Search cluster before moving on.

view_weekBack to the pattern page
LeetCode 33. Search in Rotated Sorted Array Guide | Interview AiBox