33. Search in Rotated Sorted Array
Explanation
To solve this problem in O(log n) runtime complexity, we can use a modified binary search algorithm. We can divide the rotated array into two halves. One of the halves must be sorted. We can then check if the target value lies within the sorted half or the unsorted half based on some conditions. We adjust the binary search accordingly based on which half the target value might lie in.
- We compare the target value with the values at the start, middle, and end indices of the array to determine which half is sorted.
- Based on the sorted half, we check if the target value lies within the range of the sorted half. If it does, we perform binary search in that half. Otherwise, we search in the other half.
- We repeat this process until we find the target value or determine that it does not exist in the array.
Time complexity: O(log n) Space complexity: O(1)
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;
}
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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.