Loading...
Loading...
Learn how to solve the rotated sorted array problem in O(log n) — including what interviewers really look for, common mistakes that cost candidates the offer, and exactly how to talk through it.
Here's the setup: you're given a sorted array that's been rotated at some unknown pivot point, and you need to find a target value. Return its index, or -1 if it doesn't exist.
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1This shows up constantly at FAANG interviews — and here's why interviewers reach for it: it's not enough to memorize binary search. You have to adapt it. That's exactly the signal they're hunting for. Can you take a known pattern and apply it to a messier, real-world-ish constraint? That's what separates a strong candidate from someone who just crammed LeetCode.
When I was coaching a candidate preparing for their Google loop last year, this was the exact problem that tripped them up in a mock session. Not because they didn't know binary search — they absolutely did. They panicked because the array "wasn't normal." Let's make sure that doesn't happen to you.
Before we touch any code, let's talk about what's actually being evaluated here.
The interviewer is checking whether you can:
A strong answer: candidate immediately observes the rotation doesn't break binary search entirely, articulates the "one half is always sorted" insight unprompted, and writes clean code with correct boundary conditions on the first try.
A weak answer: candidate stares at the problem, says "it's not sorted so I guess O(n)?" or jumps straight to code without explaining their approach. Even if the code works, silence during a binary search problem is a yellow flag.
Here's the thing most people miss: they see a rotated array and think "the sorting is broken, binary search won't work." That's the wrong mental model.
The rotation doesn't destroy all the sorted structure — it just splits it. At any mid point you pick:
One of the two halves will always be perfectly sorted.
That's your anchor. You don't need to find the pivot explicitly. You don't need a two-pass approach. You just need to:
midEvery iteration cuts the search space in half. That's your O(log n) right there.
Let's walk through the logic before looking at code, because understanding why each line exists will help you reconstruct this under pressure.
Step 1: Set l = 0, r = nums.length - 1. Standard binary search setup.
Step 2: While l <= r, compute mid = l + (r - l) / 2. The l + (r - l) / 2 form avoids integer overflow — mention this to your interviewer, it's a small detail that signals experience.
Step 3: If nums[mid] == target, you're done. Return mid.
Step 4: Determine which half is sorted:
nums[l] <= nums[mid], the left half is sortedStep 5: Check if the target falls within the sorted half's range:
nums[l] <= target < nums[mid]? If yes, search left. Otherwise, go right.nums[mid] < target <= nums[r]? If yes, search right. Otherwise, go left.Step 6: If the loop exits without finding the target, return -1.
class Solution {
public int search(int[] nums, int target) {
int l = 0;
int r = nums.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == target) {
return mid;
}
// Left half is sorted
if (nums[l] <= nums[mid]) {
if (nums[l] <= target &&
Here's the same logic in Python if that's your language of choice:
def search(nums: list[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l <= r:
mid = l + (r - l) // 2
if nums[mid] == target:
return mid
# Left half is sorted
if nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid
Let's trace through nums = [4,5,6,7,0,1,2], target = 0.
| Iteration | l | r | mid | nums[mid] | Action |
|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 7 | Left [4,5,6,7] sorted. 0 not in [4,7). Go right → l=4 |
| 2 | 4 | 6 | 5 | 1 | Right [1,2] sorted. 0 not in (1,2]. Go left → r=4 |
| 3 | 4 | 4 | 4 | 0 | Match! Return 4 |
Notice how each step confidently eliminates half the array. That's the story you want to tell your interviewer — "I always know which half to eliminate, and here's why."
This is the section that'll save you. These are the exact failure modes I see over and over again.
l < r instead of l <= r#This skips the single-element case. If your target happens to be the last remaining element after all the eliminations, l == r, and l < r exits early without checking it. You return -1 when the answer is right there. Always use l <= r.
// ❌ This breaks on small arrays like [3, 1]
if (nums[l] < nums[mid])
// ✅ Use <=
if (nums[l] <= nums[mid])When the array has two elements and l == mid, strict < fails. The <= handles the edge case where mid equals l.
I've seen candidates write something like this in a panic:
// ❌ Not valid Java/Python syntax, and logically ambiguous
if (nums[l] < target < nums[mid])Always be explicit:
// ✅ Clear, unambiguous
if (nums[l] <= target && target < nums[mid])Think carefully about whether each comparison should be < or <=. The target can equal nums[l], but nums[mid] is already handled by the early return above it.
A common trap is thinking, "I'll find the rotation point first, then do binary search on each half." That's two passes, more complex code, and unnecessary. The single-pass approach above handles everything in one loop. If you go down the pivot-hunting road in an interview, you're writing more code and introducing more bugs. Keep it simple.
The standard problem guarantees no duplicates. But a common follow-up is "what if duplicates are allowed?" (LeetCode 81). The key difference: when nums[l] == nums[mid], you can't determine which half is sorted, so you have to do l++ and shrink the window one step at a time. Worst case becomes O(n). Know this going in.
Your verbal communication is half the evaluation. Here's exactly how I'd coach you to walk through this:
Opening (after reading the problem):
"Okay, so the array is sorted but rotated at some pivot. My first instinct is binary search since we need O(log n). The rotation complicates it, but here's the key observation: at any midpoint, one of the two halves has to be fully sorted. So I can still use binary search — I just need to figure out which half is sorted and whether my target falls in that range."
While coding:
"I'm using
l <= rhere because I want to check the single-element case. And for detecting the sorted half, I'll usenums[l] <= nums[mid]— the<=handles the edge case wherelandmidare the same index."
After coding, proactively:
"Let me trace through the first example to verify... [walk through the dry run]. And I should think about edge cases: empty array — the while loop just never runs, so we return -1. Single element —
l == r == mid, we check it directly. Target at the boundaries — handled by the<=comparisons."
This kind of narration shows the interviewer you understand why your code works, not just that it works.
Interviewers almost always have a follow-up queued up. Here's what to expect and how to handle it:
"What's your time and space complexity?" Easy: O(log n) time because we halve the search space each iteration. O(1) space — pure iterative, no recursion or auxiliary data structures.
"What if the array has duplicates?" (LeetCode 81)
This is the real test. When nums[l] == nums[mid], you can't tell which half is sorted. Your only safe move is l++. Worst case degrades to O(n), but average case is still much better.
"Can you find the rotation index (the minimum element)?" (LeetCode 153)
Same family of problems. Modified binary search: if nums[mid] > nums[r], the minimum is in the right half. Otherwise it's in the left (including mid). Connects directly to this problem.
"What if you need to search in a rotated array with no information — not even the length?" Rare, but shows up occasionally. You'd need to first find the bounds using exponential search, then apply this approach.
l == mid this condition fails. Let me fix the comparison to <=."<= vs < decision should be something you can defend if asked.| Metric | Value | Reason |
|---|---|---|
| Time | O(log n) | Search space halves each iteration |
| Space | O(1) | Iterative, no extra data structures |
| Worst case (no dupes) | O(log n) | Guaranteed halving |
| Worst case (with dupes) | O(n) | May need to increment l one at a time |
Here's what to burn into memory before your next interview:
l <= r to avoid missing the single-element case<= when detecting sorted half (nums[l] <= nums[mid]) to handle l == midThis problem is genuinely one of the best binary search problems to master because it teaches you to work with partial structure rather than perfect structure. Once you internalize the "one half is always sorted" insight, a whole family of rotated array problems opens up. Nail this one, and you'll recognize the pattern every time it shows up dressed in different clothes.