3.8 Search in Rotated Sorted Array
3.8.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 33
- Difficulty: Medium
- URL: https://leetcode.com/problems/search-in-rotated-sorted-array/
- Tags: Grind 75, Blind 75, NeetCode 150
- Techniques: Divide and Conquer, Binary Search, Array
3.8.2 Description
Given an ascending-sorted array that has been rotated at an unknown pivot, search for a target value. If found, return its index; otherwise return -1. The array contains no duplicates, and the algorithm must run in O(log n).
3.8.3 Examples
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: -1
3.8.4 Constraints
1 <= nums.length <= 10^4-10^4 <= nums[i], target <= 10^4- All elements are distinct
3.8.5 Solution - Modified Binary Search
3.8.5.1 Walkthrough
At each step, a sorted half still exists. Compare nums[mid] with nums[left] to detect which side is sorted. If the target lies within that half, keep it; otherwise discard it and continue searching the other half.
3.8.5.3 Implementation Steps
- Set
left = 0,right = n - 1. - While
left <= right:mid = left + (right - left) / 2.- If
nums[mid] == target, returnmid. - If left half is sorted (
nums[left] <= nums[mid]):- If
targetin[nums[left], nums[mid]), setright = mid - 1elseleft = mid + 1.
- If
- Else the right half is sorted:
- If
targetin(nums[mid], nums[right]], setleft = mid + 1elseright = mid - 1.
- If
- Return
-1.
3.8.5.4 Code - Java
public int search(int[] nums, int target) {
int left = 0;
int 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 (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else {
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}