01
Problem Statement
There is an integer array nums that was sorted in ascending order with distinct values but then rotated at an unknown pivot (e.g. [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). Given target, return its index in nums, or -1 if it is not in nums. You must write an O(log n) algorithm.
- In a rotated sorted array, one of the two halves
[left..mid]or[mid..right]is always sorted. We can check which half containstargetand narrow the search.
02
Key Observations
- At each step,
nums[mid]splits the range. Either the left half[left..mid]is sorted (nums[left] <= nums[mid]) or the right half[mid..right]is sorted. If the left half is sorted andtargetis in[nums[left], nums[mid]], search left; otherwise search right. If the right half is sorted andtargetis in[nums[mid], nums[right]], search right; otherwise search left. - We always eliminate one half, so the search is O(log n).
03
Approach
High-level: Binary search. If nums[left] <= nums[mid], the left half is sorted: if nums[left] <= target < nums[mid], search left (right = mid - 1); else search right (left = mid + 1). If nums[mid] < nums[right], the right half is sorted: if nums[mid] < target <= nums[right], search right; else search left. Return -1 if not found.
Steps:
left = 0,right = n - 1. Whileleft <= right:mid = left + (right - left) / 2. Ifnums[mid] == targetreturnmid.- If
nums[left] <= nums[mid]: ifnums[left] <= target && target < nums[mid],right = mid - 1; elseleft = mid + 1. Else: ifnums[mid] < target && target <= nums[right],left = mid + 1; elseright = mid - 1. - Return -1.
04
Implementation
Java
public int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[left] <= nums[mid]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
else {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
return -1;
}05
Test Cases
Example 1
Input
nums = [4,5,6,7,0,1,2], target = 0
Expected
4Explanation
0 at index 4.
06
Complexity Analysis
- Time: O(log n).
- Space: O(1).
07
Follow-ups
- Duplicate values: worst case O(n).