Search in Rotated Sorted Array
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
nums is a sorted array of distinct integers that may have been rotated at an unknown point. Given nums and a target, return the index of target, or -1 if it isn't there.
Your algorithm must run in O(log n).
Understand the problem
- Rotated means the sorted array was "cut" somewhere and the two pieces swapped:
[0, 1, 2, 4, 5, 6, 7]can become[4, 5, 6, 7, 0, 1, 2]. (If this is new, solve Find Minimum in Rotated Sorted Array first.) - You don't know where the cut is. It might not be rotated at all.
- You return the position of
target, or-1if it's missing. - O(log n) rules out checking every element: you need binary search, throwing away half of the range each step.
Example 1
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
Output: 40 sits at index 4.
Example 2
Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
Output: -13 isn't in the array.
Example 3
Input: nums = [1], target = 0
Output: -1Constraints
1 <= nums.length <= 5000-10^4 <= nums[i], target <= 10^4- All values are distinct.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Binary search, but at each step figure out which half is normally sorted, check whether the target falls inside that half's range, and keep only the half that could contain it.
The naive approach (and why it's not enough)
- Scan every element: O(n). Correct, but the problem demands O(log n).
- Find the rotation point, then binary search the right piece: works in O(log n), but takes two separate binary searches. There's a neater single pass.
The key insight
Normal binary search relies on "everything left of mid is smaller, everything right is bigger". A rotation breaks that rule for one of the two halves, but never both:
[4, 5, 6, 7, 0, 1, 2]
↑ mid
left half [4, 5, 6, 7] → sorted (4 <= 7)
right half [7, 0, 1, 2] → not sorted (contains the drop)So at every step:
- Find the sorted half: if
nums[left] <= nums[mid], it's the left one; otherwise it's the right one. - In the sorted half, checking "could the target be here?" takes two comparisons: is
targetbetween its smallest and largest values? - If yes, keep that half. If no, keep the other half.
Step by step
nums = [4, 5, 6, 7, 0, 1, 2], target = 0:
left | right | mid (value) | Sorted half | Is 0 in it? | Keep |
|---|---|---|---|---|---|
| 0 | 6 | 3 (7) | left [4..7] (since 4 <= 7) | 4 <= 0 < 7? no | right: left = 4 |
| 4 | 6 | 5 (1) | left [0..1] (since 0 <= 1) | 0 <= 0 < 1? yes | left: right = 4 |
| 4 | 4 | 4 (0) | nums[mid] === 0 ✅ | return 4 |
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(log n). Each step halves the range.
- Memory: O(1).
Common mistakes
- Using
<instead of<=innums[left] <= nums[mid]. Whenleft === mid(a range of one or two elements), the left "half" is a single element, which counts as sorted. With<, you'd pick the wrong half. - Getting the range checks' edges wrong. In the sorted left half, the target is inside if
nums[left] <= target < nums[mid]. We already knownums[mid] !== target, so themidend is excluded. - Forgetting the
-1case. If the loop ends without finding it, the target isn't there.
Going deeper
A follow-up interviewers like: what if values can repeat? Then nums[left] === nums[mid] doesn't tell you which half is sorted (think [1, 1, 1, 3, 1]). The usual fix is to shrink by one (left++) in that case, which makes the worst case O(n).
Reference solution
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
export default function search(nums, target) {
let left = 0
let right = nums.length - 1
while (left <= right) {
const mid = Math.floor((left + right) / 2)
if (nums[mid] === target) return mid
if (nums[left] <= nums[mid]) {
// The LEFT half nums[left..mid] is sorted normally.
// Is the target inside its range? Then keep the left half, else the right.
if (nums[left] <= target && target < nums[mid]) right = mid - 1
else left = mid + 1
} else {
// Otherwise the RIGHT half nums[mid..right] is sorted normally.
if (nums[mid] < target && target <= nums[right]) left = mid + 1
else right = mid - 1
}
}
// The range ran out without finding the target.
return -1
}export default function search(nums: number[], target: number): number {
let left = 0
let right = nums.length - 1
while (left <= right) {
const mid = Math.floor((left + right) / 2)
if (nums[mid] === target) return mid
if (nums[left] <= nums[mid]) {
// The LEFT half nums[left..mid] is sorted normally.
// Is the target inside its range? Then keep the left half, else the right.
if (nums[left] <= target && target < nums[mid]) right = mid - 1
else left = mid + 1
} else {
// Otherwise the RIGHT half nums[mid..right] is sorted normally.
if (nums[mid] < target && target <= nums[right]) left = mid + 1
else right = mid - 1
}
}
// The range ran out without finding the target.
return -1
}def search(nums: list[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
# The LEFT half nums[left..mid] is sorted normally.
# Is the target inside its range? Then keep the left half, else the right.
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
# Otherwise the RIGHT half nums[mid..right] is sorted normally.
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
# The range ran out without finding the target.
return -1