Search in Rotated Sorted Array
How the interviewer asks it
“A sorted array of distinct numbers has been rotated at an unknown pivot. Given a target, return its index or -1, in O(log n) time.”
0 4 5 6 7 0 1 2
4
In the practice room your code reads the input from standard input, and Run checks it against tests like this one. Try it now in your browser, in Python or JavaScript.
Typed drills are free and unlimited: the AI scores your answer against the outline below.
What the interviewer is looking for
- You see that at any midpoint at least one half is sorted.
- A precise check of whether the target lies inside the sorted half.
- Consistent loop bounds and mid calculation, with no infinite loop on two elements.
- You test arrays that are not rotated at all.
How to structure your answer
- 01
Clarify
Are values distinct? Can the array be empty or not rotated?
- 02
Find the sorted half
Compare nums[lo] with nums[mid]. If nums[lo] ≤ nums[mid], the left half is sorted; otherwise the right half is.
- 03
Narrow
If the target lies within the sorted half's range, search there; otherwise search the other half.
- 04
Test
[4,5,6,7,0,1,2] with targets 0, 3 and 4, plus a one-element and an unrotated array.
- 05
Complexity
O(log n) time, O(1) space.
Best answers from candidates
No candidate answers yet. Type yours, and if it scores 6 or more you can show it here without your name.
Answers are shared by candidates, without names, after a privacy check. Add yours
Common mistakes
- Using < instead of ≤ when checking the sorted half, which breaks on two elements.
- Finding the pivot first and then forgetting to map indices back.
- Not saying what changes when duplicates are allowed (worst case becomes O(n)).
Follow-up questions to expect
- Duplicates are allowed. What is the worst case now?
- Find the minimum element of the rotated array.
Now answer it out loud
Max will ask you this exact question, listen to your answer, push on the weak spots with follow-ups like the ones above, and score you when you finish.
Practice with MaxFree: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.
More coding interview questions
Preparing for this round? Read how to prepare for a coding interview: a four-week DSA plan.