← DSA
MEDIUM

Search in Rotated Sorted Array

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.

Example

Input nums = [4,5,6,7,0,1,2], target = 0
Output 4

Key Pointers

Step-by-Step Analysis

  1. Set left = 0, right = len(nums) - 1.
  2. While left has not passed right: compute mid; if nums[mid] equals the target, return mid.
  3. If 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.
  4. Otherwise the right half is sorted: when the target falls within that sorted range, search the right half; otherwise search the left half.
  5. If the loop ends without a match, return -1.

Complexity

Time: O(log n) — Space: O(1)

Code

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 -1

Code Explanation

How the solution above works, piece by piece.

  1. At every mid, at least one of the two halves is fully sorted.
  2. If nums[mid] is the target, done.
  3. 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.
  4. Otherwise the right half is sorted: same test on nums[mid] .. nums[right].
  5. Checking a range is only reliable on a sorted half, which is why the code first identifies that half. Still one half discarded per step: O(log n).

Visual Walkthrough

Running it on nums = [4, 5, 6, 7, 0, 1, 2], target = 0:

trace40516273041526left half 4..7 sorted; 0 not inside → go right4567012left half 0..1 sorted; 0 inside → go left4567012nums[4] = 0 → return 4
Step 1: the left half 4..7 is sorted and 0 isn't in it, so go right. Step 2: the right half 1..2 is sorted and 0 isn't in it, so go left. Step 3 lands on 0 at index 4.
midfound

Video Explanation

NeetCode — Search in Rotated Sorted Array, LeetCode 33