The Search in Rotated Sorted Array problem involves finding a target element in a sorted array that has been rotated at an unknown pivot. The goal is to locate the target in O(log N)
time using binary search.
class Solution {
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; // Target found
}
// Determine which half is sorted
if (nums[left] <= nums[mid]) { // Left half is sorted
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1; // Search left half
} else {
left = mid + 1; // Search right half
}
} else { // Right half is sorted
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1; // Search right half
} else {
right = mid - 1; // Search left half
}
}
}
return -1; // Target not found
}
}
O(log N)
โ Halving the search space at each step.Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Explanation:
- The target 0 is found at index 4.