Search in a Rotated Sorted Array
Table of Contents + β
This is a classic interview question. It looks scary at first. A sorted array got twisted around. Now you have to find a number in it fast. The interviewer is not testing if you can search. They want to see if you can still use binary search even when the array is not fully sorted anymore.
π The Problem
You start with a sorted array. Then someone rotates it at some unknown point. Rotating means they cut the array at one spot and move the front part to the back. So [0, 1, 2, 4, 5, 6, 7] might become [4, 5, 6, 7, 0, 1, 2].
Now you get a target number. You have to return the index where it sits. If it is not there, return -1. And the interviewer wants it in O(log n) time.
Here is what that looks like:
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0Output: 4
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3Output: -1O(log n) means the time grows very slowly even when the array gets huge. Every step should throw away half of what is left. That is the hint pointing straight at binary search.
π§ The Simple Idea First
The obvious way is to just walk through the whole array. Check every element one by one. If you find the target, return its index. If you reach the end, return -1.
That works and it is easy to write. But it looks at every element, so it is O(n) time. The interviewer clearly asked for O(log n). So this is the version you mention out loud, then say βbut we can do better.β It shows you know the easy path exists. You are just choosing the smarter one.
π― The Modified Binary Search Way
Normal binary search needs a fully sorted array. Our array is rotated, so it is not fully sorted. But here is the key fact that saves us.
If you cut the rotated array at the middle, one half is always sorted. It is impossible for both halves to be broken at the same time. The rotation point sits in only one of the two halves. The other half stays in clean sorted order.
So the plan is simple. Find the middle. Figure out which half is the sorted one. Then check if the target falls inside that sorted half. If yes, search there. If no, search the other half. Either way you drop half the array each step. That gives you O(log n).
Letβs walk through [4, 5, 6, 7, 0, 1, 2] looking for 0.
left = 0,right = 6, somid = 3. The value atmidis7.- Is the left half sorted? Compare
nums[left]withnums[mid]:4 <= 7is true. So the left side[4, 5, 6, 7]is sorted. - Is the target
0inside that sorted range, between4and7? No. So0cannot be on the left. Moveleft = mid + 1, nowleft = 4. - New range is
[0, 1, 2].mid = 5, value1. Left half[0, 1]is sorted. Is0between0and1? Yes. So moveright = mid - 1, nowright = 4. - Now
left = 4,right = 4,mid = 4, value0. That equals the target. Return4.
See how each step cut the work in half? That is the whole idea.
Steps to search a rotated sorted array
Letβs write the steps down before any code.
- Set
left = 0andright = n - 1. - While
left <= right:- Find
mid = left + (right - left) / 2. - If
nums[mid]equals the target, returnmid. - If
nums[left] <= nums[mid], the left half is sorted.- If the target sits between
nums[left]andnums[mid], moveright = mid - 1. Otherwise moveleft = mid + 1.
- If the target sits between
- Else the right half is sorted.
- If the target sits between
nums[mid]andnums[right], moveleft = mid + 1. Otherwise moveright = mid - 1.
- If the target sits between
- Find
- If the loop ends, the target is not there, so return
-1.
Use less-than-or-equal in the checks
When you test if the target is inside the sorted half, use <= on the boundary, not just <. The endpoints nums[left] and nums[right] are real values in the array. If you skip them with a strict less-than, you can miss the target sitting right on the edge.
Code to search a rotated sorted array
Now letβs see it in every language.
# returns the index of target, or -1 if not founddef search(nums, target): left = 0 right = len(nums) - 1
while left <= right: mid = left + (right - left) // 2
if nums[mid] == target: return mid
# is the left half sorted? if nums[left] <= nums[mid]: # is target inside the sorted left half? if nums[left] <= target < nums[mid]: right = mid - 1 else: left = mid + 1 else: # the right half is sorted if nums[mid] < target <= nums[right]: left = mid + 1 else: right = mid - 1
return -1
def main(): nums = [4, 5, 6, 7, 0, 1, 2] print("Index of 0:", search(nums, 0)) print("Index of 3:", search(nums, 3))
if __name__ == "__main__": main()The output of the above code will be:
Index of 0: 4Index of 3: -1β±οΈ Time and Space Complexity
| Approach | Time | Space |
|---|---|---|
| Linear scan (brute force) | O(n) | O(1) |
| Modified binary search | O(log n) | O(1) |
Both ways use only a few variables, so both are O(1) extra space. The real difference is time. The linear scan checks every element, so it is O(n). The modified binary search throws away half the array each step, so it is O(log n). That is the answer the interviewer wants.
Say the key insight out loud
The one sentence the interviewer wants to hear is this: βAfter splitting at the middle, one half is always sorted.β Say it early. It tells the interviewer you understand why binary search still works on a rotated array, not just that you memorized the code.
π§© Key Takeaways
- β A rotated sorted array still lets you use binary search, because one half is always sorted after you split at the middle.
- β At each step, find the sorted half, then check if the target lies inside it to decide which way to go.
- β
Use
<=on the boundary checks so you do not miss a target sitting on an endpoint. - β Time is O(log n) and extra space is O(1).
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
After you split a rotated sorted array at the middle, what is always true?
Why: The rotation point lives in only one half, so the other half is always in clean sorted order.
- 2
Why is a plain linear scan a weaker answer for this problem?
Why: The linear scan works but checks every element, so it is O(n). The interviewer asked for O(log n).
- 3
Once you know which half is sorted, what do you check next?
Why: If the target is inside the sorted half's range, you search there; otherwise you search the other half.
- 4
What does the function return when the target is not in the array?
Why: When the loop ends without a match, the target is not present, so the function returns -1.
π Whatβs Next?
Now that you can search a twisted array, build on the same idea:
- Binary Search is the clean foundation this whole trick is built on.
- Find First and Last Position uses binary search again to find a range, not just one index.
Once you really get βone half is always sorted,β a lot of rotated-array problems stop feeling scary.