Search in Rotated Sorted Array
A medium Arrays problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Search for a target value in a sorted array that has been rotated at an unknown pivot, returning its index or -1 if absent.
Example 1
- Input
- nums = [4,5,6,7,0,1,2], target = 0
- Output
- 4
- Why
- The value 0 is located at index 4 in the rotated array.
Example 2
- Input
- nums = [4,5,6,7,0,1,2], target = 3
- Output
- -1
- Why
- The value 3 does not appear anywhere in the collection.
Example 3
- Input
- nums = [1], target = 0
- Output
- -1
- Why
- The lone element does not match the desired target.
Constraints
- 1 <= nums.length <= 5000
- -10^4 <= nums[i] <= 10^4
- -10^4 <= target <= 10^4
How to think about it
Updated 2026-09-09No matter where a rotated array is cleaved in half, at least one of the two halves remains strictly sorted. Checking whether the target falls within the boundary values of that ordered half tells you whether to search inside it or discard it completely. That single branching rule preserves the logarithmic halving property at every step.
Approaches, worst first
Linear scanning
time O(n) · space O(1)
Walk through the array from start to finish checking each value against the target. Straightforward and ignores rotation completely, but discards the sorted structure and inspects every element in the worst case.
Pivot location followed by binary search
time O(log n) · space O(1)
Find the rotation pivot index first via binary search, identify which of the two strictly ascending subsegments contains the target range, and execute a standard binary search on that segment. Achieves logarithmic runtime across two separate phases.
Direct one-pass binary searchWrite this one
time O(log n) · space O(1)
Compute mid between low and high. If nums[mid] == target, return mid. Otherwise, determine whether the left half [low..mid] or right half [mid..high] is sorted, test whether the target lies strictly within that sorted interval, and narrow the bounds accordingly.
Where people lose marks · 3
- Using `<` instead of `<=` when checking if the target lies within the boundaries of the sorted half, missing targets positioned at the ends.
- Assuming the left half is sorted whenever nums[mid] > target, which fails when the rotation pivot sits between low and mid.
- Dividing mid without accounting for odd or even spans, causing infinite loops when low and high differ by 1.
Full solution
Direct one-pass binary search: at each mid, one of the two halves is guaranteed sorted, so check the target against that half's boundary values to decide which side to keep. This is the answer an interview expects over locating the pivot first as a separate phase.
Python
def search(nums: list[int], target: int) -> int:
low, high = 0, len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
if nums[low] <= nums[mid]:
# Left half is sorted.
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
else:
# Right half is sorted.
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
JavaScript
function search(nums, target) {
let low = 0;
let high = nums.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (nums[mid] === target) return mid;
if (nums[low] <= nums[mid]) {
// Left half is sorted.
if (nums[low] <= target && target < nums[mid]) {
high = mid - 1;
} else {
low = mid + 1;
}
} else {
// Right half is sorted.
if (nums[mid] < target && target <= nums[high]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
}
return -1;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .