Search in Rotated Sorted Array (LeetCode 33): Solution and Explanation

Medium
Array
Binary Search

An array of distinct integers was sorted in ascending order and then rotated at some unknown pivot, so it looks like two sorted runs glued together. Given a target, return its index or -1, and do it in logarithmic time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A linear scan finds the target in O(n) and ignores the structure entirely. The requirement for O(log n) is a strong hint that binary search still applies, even though the array as a whole is no longer sorted.

The observation that unlocks it is this: whenever you pick a midpoint in a rotated array, at least one of the two halves on either side of it is perfectly sorted. The rotation point can only fall in one half, so the other half is a clean ascending run. You can tell which half is sorted by comparing nums[l] with nums[mid]. If nums[l] <= nums[mid], the left half has no break in it.

Once you know one half is sorted, you can check whether the target lies inside it with two simple comparisons against that half's endpoints. If it does, search there. If it does not, the target can only be in the other half, rotated or not. Either way you discard half of the remaining range every iteration, which is exactly what binary search needs.

Approach: Modified binary search

  1. Set l = 0 and r = len(nums) - 1 and loop while l <= r.
  2. Compute mid and return it immediately if nums[mid] == target.
  3. If nums[l] <= nums[mid], the left half is sorted. If the target is greater than nums[mid] or smaller than nums[l], it cannot be in that half, so move l = mid + 1; otherwise move r = mid - 1.
  4. Otherwise the right half is sorted. If the target is smaller than nums[mid] or greater than nums[r], it cannot be in the right half, so move r = mid - 1; otherwise move l = mid + 1.
  5. If the loop ends without a match, return -1.

Step-by-step example

nums = [4,5,6,7,0,1,2], target = 0
  1. l = 0, r = 6, mid = 3, nums[3] = 7. Not the target.
  2. nums[0] = 4 <= 7, so the left half [4,5,6,7] is sorted. The target 0 is less than nums[l] = 4, so it is not there. Set l = 4.
  3. l = 4, r = 6, mid = 5, nums[5] = 1. nums[4] = 0 <= 1, so [0,1] is sorted, and 0 lies between 0 and 1. Set r = 4.
  4. l = 4, r = 4, mid = 4, nums[4] = 0 equals the target. Return 4.

Code: Python, Java, C++

1class Solution:
2    def search(self, nums: List[int], target: int) -> int:
3        l, r = 0, len(nums) - 1
4        
5        while l <= r:
6            mid = (l + r) // 2
7            if nums[mid] == target:
8                return mid
9            
10            # Left sorted portion
11            if nums[l] <= nums[mid]:
12                if target > nums[mid] or target < nums[l]:
13                    l = mid + 1
14                else:
15                    r = mid - 1
16            # Right sorted portion
17            else:
18                if target < nums[mid] or target > nums[r]:
19                    r = mid - 1
20                else:
21                    l = mid + 1
22        return -1

Time and space complexity

Time

O(log n)

Every iteration discards half of the remaining range, so there are at most about log2(n) iterations, each doing constant work.

Space

O(1)

Only the pointers l, r and mid are stored, regardless of the input size.

Other approaches

Find the pivot, then binary search (time O(log n), space O(1))

First binary search for the index of the minimum element, which is the rotation point. Then decide which of the two sorted runs could hold the target and run an ordinary binary search on it. It is two passes instead of one but each piece is easier to reason about.

Linear scan (time O(n), space O(1))

Walk the array and return the first index where the value equals the target. It is trivially correct and fine for tiny inputs, but it ignores the sorted structure and misses the required bound.

Common mistakes

  • Using nums[l] < nums[mid] instead of <=. When l == mid the left half is a single element and counts as sorted; the strict check sends the search the wrong way on two-element ranges.
  • Checking only one bound of the sorted half. You need both target < nums[l] and target > nums[mid] (or the mirrored pair on the right) to rule a half out.
  • Comparing the target against nums[0] or nums[-1] instead of the current nums[l] and nums[r], which stops working after the first iteration narrows the range.
  • Applying this code to arrays with duplicates. When nums[l] == nums[mid] == nums[r] you cannot tell which half is sorted, which is why the duplicate version needs extra handling.

Frequently asked questions

How do you know which half of a rotated array is sorted?

Compare the left end of the range with the midpoint. If nums[l] <= nums[mid], the rotation break is not between them, so the left half is sorted. Otherwise the break is in the left half, which means the right half from mid to r is sorted.

Why is the time complexity O(log n) if the array is not fully sorted?

Each step still eliminates half the remaining range. Because one half is always sorted, two comparisons tell you whether the target can be in it, and the other half is chosen otherwise. Halving the range each step gives logarithmic time.

What changes if the array contains duplicates?

Duplicates can make nums[l], nums[mid] and nums[r] all equal, and then you cannot tell which side is sorted. The usual fix is to shrink the range by one from the left in that case, which keeps correctness but degrades the worst case to O(n).

Do I need to find the rotation point first?

No. The one-pass version decides which half is sorted at every step, so it never needs the pivot index explicitly. Finding the pivot first is a valid alternative that some people find easier to debug.