Binary Search
Medium
Search in Rotated Sorted Array
Search for a target value in an array that has been rotated at an unknown pivot.
15 min
Solve on LeetCodeProblem Understanding
A sorted array (e.g., [0, 1, 2, 4, 5, 6, 7]) is rotated at some pivot.
- Example Rotation:
[4, 5, 6, 7, 0, 1, 2].
Given this rotated array and a target target, return the index of target. If not found, return -1.
You must write an algorithm with O(log n) runtime complexity.
Examples
- ([4,5,6,7,0,1,2]), target = 0 -> Index 4.
- ([4,5,6,7,0,1,2]), target = 3 -> -1.
Attempt 1: Brute Force
Simply iterate through the array and look for the target.
for(let i=0; i<nums.length; i++) {
if (nums[i] === target) return i;
}
return -1;
Complexity: O(n).
This is trivial but violates the O(log n) requirement.
The Intuition: Half is always sorted
Even though the array is rotated, at any split (midpoint), at least one half must be sorted.
Consider [4, 5, 6, 7, 0, 1, 2]:
- Mid at index 3 (Value 7).
- Left part
[4, 5, 6, 7]is sorted (4 <= 7). - Right part
[7, 0, 1, 2]is NOT sorted.
- Left part
We can use this property:
- Identify which half is sorted.
- Check if the
targetlies within that sorted half's range. - If yes, search that half.
- If no, search the other half.
Interactive Visualization
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Attempt 1: Brute Force
- The Intuition: Half is always sorted
- Interactive Visualization
- Dry Run
- The Solution Template
- Edge Cases
- Time & Space Analysis
- Summary
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
