Search in Rotated Sorted Array (LeetCode 33): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Set
l = 0andr = len(nums) - 1and loop whilel <= r. - Compute
midand return it immediately ifnums[mid] == target. - If
nums[l] <= nums[mid], the left half is sorted. If the target is greater thannums[mid]or smaller thannums[l], it cannot be in that half, so movel = mid + 1; otherwise mover = mid - 1. - Otherwise the right half is sorted. If the target is smaller than
nums[mid]or greater thannums[r], it cannot be in the right half, so mover = mid - 1; otherwise movel = mid + 1. - If the loop ends without a match, return -1.
Step-by-step example
nums = [4,5,6,7,0,1,2], target = 0
- l = 0, r = 6, mid = 3,
nums[3] = 7. Not the target. nums[0] = 4 <= 7, so the left half [4,5,6,7] is sorted. The target 0 is less thannums[l] = 4, so it is not there. Set l = 4.- 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. - l = 4, r = 4, mid = 4,
nums[4] = 0equals 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 -11class Solution {
2 public int search(int[] nums, int target) {
3 int l = 0, r = nums.length - 1;
4
5 while (l <= r) {
6 int mid = l + (r - l) / 2;
7 if (nums[mid] == target) return mid;
8
9 // Left sorted
10 if (nums[l] <= nums[mid]) {
11 if (target > nums[mid] || target < nums[l]) {
12 l = mid + 1;
13 } else {
14 r = mid - 1;
15 }
16 }
17 // Right sorted
18 else {
19 if (target < nums[mid] || target > nums[r]) {
20 r = mid - 1;
21 } else {
22 l = mid + 1;
23 }
24 }
25 }
26 return -1;
27 }
28}1class Solution {
2public:
3 int search(vector<int>& nums, int target) {
4 int l = 0, r = nums.size() - 1;
5
6 while (l <= r) {
7 int mid = l + (r - l) / 2;
8 if (nums[mid] == target) return mid;
9
10 // Left sorted
11 if (nums[l] <= nums[mid]) {
12 if (target > nums[mid] || target < nums[l]) {
13 l = mid + 1;
14 } else {
15 r = mid - 1;
16 }
17 }
18 // Right sorted
19 else {
20 if (target < nums[mid] || target > nums[r]) {
21 r = mid - 1;
22 } else {
23 l = mid + 1;
24 }
25 }
26 }
27 return -1;
28 }
29};Time and space complexity
O(log n)
Every iteration discards half of the remaining range, so there are at most about log2(n) iterations, each doing constant work.
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<=. Whenl == midthe 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]andtarget > nums[mid](or the mirrored pair on the right) to rule a half out. - Comparing the target against
nums[0]ornums[-1]instead of the currentnums[l]andnums[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.