Search in Rotated Sorted Array solution explained
To search a rotated sorted array in O(log n), run binary search but, at each step, first work out which half of the range is in order: if values[low] <= values[mid], the left half is sorted, otherwise the right half is. Check whether the target falls inside the sorted half's value range; if it does, search there, and if not, search the other half.
By Evin JohnPublished 7 min read
The problem, restated
An increasing list of distinct integers was rotated: some suffix was moved to the front, possibly an empty one. You get the rotated list and a target. Return the target's index in the rotated list, or -1 if it is absent, and do it in logarithmic time. You are not told where the rotation happened.
| Rotated list | Target | Result |
|---|---|---|
| [15, 18, 21, 3, 7, 9] | 7 | 4 |
| [15, 18, 21, 3, 7, 9] | 18 | 1 |
| [15, 18, 21, 3, 7, 9] | 10 | -1 |
| [8, 2] | 2 | 1 |
| [4] | 5 | -1 |
| [] | 2 | -1 |
As with any search question, clarify duplicates first. The standard version promises distinct values. With duplicates the one-pass method needs an extra case and loses its logarithmic worst case, which is a common follow-up.
What the interviewer is testing
This is one of the most common 'binary search with a twist' questions. The interviewer wants to see you reason about which part of the data still has the property binary search needs, and then write four branches without mixing up strict and non-strict comparisons. Expect to be asked to trace a small case, so pick one in advance where the rotation point is near the middle.
Two simpler answers
First, the linear scan: O(n) and it ignores the order. Second, a perfectly good logarithmic answer in two passes: binary search for the index of the minimum, which is the rotation point (the method from Find Minimum in Rotated Sorted Array), then decide which of the two sorted runs could contain the target and run ordinary binary search on that run alone.
from bisect import bisect_left
def rotated_find_two_step(values, goal):
if not values:
return -1
low, high = 0, len(values) - 1
while low < high: # locate the smallest value: the rotation point
mid = (low + high) // 2
if values[mid] > values[high]:
low = mid + 1
else:
high = mid
pivot = low
# pick the sorted run that could hold the goal, then search it normally
if goal >= values[pivot] and goal <= values[-1]:
start, end = pivot, len(values)
else:
start, end = 0, pivot
i = bisect_left(values, goal, start, end)
return i if i < end and values[i] == goal else -1Offer this if the one-pass logic does not come to you quickly. It is easy to verify and uses only pieces you already trust. Many interviewers then ask whether you can do it in a single loop.
One pass: find the half that is in order
Pick the middle of the current range. The rotation point can be in at most one of the two halves, so at least one half, low to mid or mid to high, is sorted. Compare values[low] with values[mid]: if the left end is at most the middle, the left half is sorted; otherwise the right half is. For the sorted half, you know its smallest and largest values exactly, so you can check in O(1) whether the target could be inside it. If yes, search that half. If no, the target can only be in the other half, sorted or not.
def rotated_find(values, goal):
low, high = 0, len(values) - 1
while low <= high:
mid = (low + high) // 2
if values[mid] == goal:
return mid
if values[low] <= values[mid]: # left half low..mid is in order
if values[low] <= goal < values[mid]:
high = mid - 1
else:
low = mid + 1
else: # right half mid..high is in order
if values[mid] < goal <= values[high]:
low = mid + 1
else:
high = mid - 1
return -1function rotatedFind(values, goal) {
let low = 0;
let high = values.length - 1;
while (low <= high) {
const mid = (low + high) >> 1;
if (values[mid] === goal) return mid;
if (values[low] <= values[mid]) {
if (values[low] <= goal && goal < values[mid]) high = mid - 1;
else low = mid + 1;
} else {
if (values[mid] < goal && goal <= values[high]) low = mid + 1;
else high = mid - 1;
}
}
return -1;
}The <= in values[low] <= values[mid] matters. When the range has two elements, mid equals low, so the left half is just one element and counts as sorted. With a strict <, the code would treat the right half as sorted when it may not be, and could search the wrong side. The range checks use a strict comparison against values[mid] because the middle was already checked for equality.
Tracing it
| Target | low | high | mid (value) | Sorted half | Decision |
|---|---|---|---|---|---|
| 7 | 0 | 5 | 2 (21) | Left, 15 to 21 | 7 is outside 15 to 21, go right |
| 7 | 3 | 5 | 4 (7) | Found at index 4 | |
| 18 | 0 | 5 | 2 (21) | Left, 15 to 21 | 18 is inside, go left |
| 18 | 0 | 1 | 0 (15) | Left, just 15 | 18 is not below 15, go right |
| 18 | 1 | 1 | 1 (18) | Found at index 1 |
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Linear scan | O(n) | O(1) |
| Find rotation point, then search one run | O(log n) | O(1) |
| One-pass sorted-half check | O(log n) | O(1) |
| One pass with duplicates allowed | O(n) worst case | O(1) |
Follow-up: duplicates
If values can repeat, values[low], values[mid] and values[high] can all be equal, and then neither half is provably sorted. The standard fix is to step low forward by one in that case and continue. That is correct, but a list made of one value repeated with a single different value hidden somewhere forces many single steps, so the worst case is O(n). Most interviewers mainly want you to name the problem and that bound.
Edge cases
- Empty list: return -1 without indexing.
- One element, matching and not matching.
- No rotation: the left half is always sorted, and the method behaves like plain binary search.
- Two elements in rotated order, which is where a strict
<fails. - Target equal to the first or last value of a sorted half, which tests the inclusive ends of the range checks.
- Target smaller than everything or larger than everything.
Typical mistakes
- Using
values[low] < values[mid]and getting two-element ranges wrong. - Writing
values[low] < goaland missing a target equal to the left end. - Checking the target against the unsorted half, whose minimum and maximum are not its end values.
- Searching the sorted half for the target without first checking the target could be in it.
- Forgetting that the question asks for the index in the rotated list, not in the original sorted list.
How to explain it out loud
Fictional example
- Candidate
- The rotation point is in at most one half, so whichever half doesn't contain it is sorted. I can tell which by comparing the left end with the middle.
- Candidate
- For the sorted half I know its smallest and largest values, so I check whether the target fits between them. If it does, I search there; if not, it can only be in the other half.
- Interviewer
- Why less than or equal when you compare the left end with the middle?
- Candidate
- When there are two elements left, the middle is the left end, so that single element is trivially sorted. A strict comparison would call the left side unsorted and send me the wrong way.
Related walkthroughs
The rotation-point search used in the two-pass version is explained in Find Minimum in Rotated Sorted Array. The plain loop, with its boundary conventions, is in Binary Search. For a different structure where binary search runs on stored history per key, see Time Based Key-Value Store. The full list is on the coding problems hub.
Practice support from Natively
Four branches with mixed strict and non-strict comparisons are easy to garble when you are nervous, so rehearse the trace above out loud a few times. Natively, a desktop app for Mac and Windows, transcribes each practice run, letting you compare what you said with the code you wrote. When practicing, it can also read the prompt from a screenshot and offer a starting approach to check against your own. The AI assistant for coding interviews page has the details.
Questions people ask
How do you search in a rotated sorted array in O(log n)?
Binary search, but at each step decide which half is sorted by comparing values[low] with values[mid]. If the target lies within the sorted half's range, search that half; otherwise search the other half.
Can I find the rotation point first?
Yes. Binary search for the index of the minimum, choose the sorted run that could hold the target, and binary search that run. It is two O(log n) passes and easy to verify.
Why use values[low] <= values[mid] and not <?
With two elements left, mid equals low, so the left half is one element and is sorted. A strict comparison misclassifies it and can search the wrong side.
What if the array has duplicates?
When the left, middle and right values are equal, neither half is provably sorted, so step low forward by one. That stays correct but the worst case becomes O(n).
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
