Problem Statement

Search in Rotated Sorted Array

Start with an array of numbers sorted from smallest to largest. Now imagine someone cut the array at one secret spot and moved the front chunk to the back. That is what "rotated at an unknown pivot" means. For example, [0,1,2,4,5,6,7] could become [4,5,6,7,0,1,2]. The list is no longer fully sorted, but it is two sorted pieces stuck together. You are given this rotated array nums and a number called target. Return the index (the position) where target sits in nums, or return -1 if it is not there.

mediumBinary SearchBinary SearchTime: O(log n) · Space: O(1)

Signals to notice

sorted but rotatedfind the target by cutting the range in halfone half is always sorted

Brute force first

Linear scan. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Modified binary search: determine which half is sorted, check if target is in that half. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

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

init: left=0, right=6
left=0,right=6 -> mid=3, nums[3]=7 != 0; nums[0]=4<=nums[3]=7 so LEFT half sorted; 4<=0<7? no -> left=mid+1=4
left=4,right=6 -> mid=5, nums[5]=1 != 0; nums[4]=0<=nums[5]=1 so LEFT half sorted; 0<=0<1? yes -> right=mid-1=4
left=4,right=4 -> mid=4, nums[4]=0 == target -> return 4

What must stay true

At least one half of the array around mid is always sorted after rotation. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Shape of the loop

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

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Not handling the case where target equals the boundary element of the sorted half. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Binary Search Pattern