Search in Rotated Sorted Array
You are given a sorted array that has been rotated at some unknown pivot point. This means the array was initially sorted in ascending order, but then a portion of it was moved from the beginning to the end. Your task is to efficiently search for a target value within this rotated array. This problem is a classic interview question that tests your ability to adapt binary search to non-standard scenarios.
Problem Description
You are given an array nums of integers, which was originally sorted in ascending order but has been rotated some number of times. You are also given an integer target. The goal is to determine the index of the target value within the rotated array. If the target is not found, return -1.
Key Requirements:
- The array
numsis composed of distinct integers. - The array
numsis rotated at an unknown pivot point. This means a portion of the array has been moved from the beginning to the end. - You must implement an efficient search algorithm, preferably with logarithmic time complexity (O(log n)).
- The search should handle edge cases such as an empty array, target not present, and target being the first or last element.
Expected Behavior:
The function should return the index of the target value if it exists in the array. If the target value is not found, the function should return -1.
Edge Cases to Consider:
- Empty array:
nums = [] - Array with one element:
nums = [5] - Target is the first element:
nums = [4, 5, 6, 7, 0, 1, 2], target = 4 - Target is the last element:
nums = [4, 5, 6, 7, 0, 1, 2], target = 2 - Target is the pivot element (the smallest element):
nums = [4, 5, 6, 7, 0, 1, 2], target = 0 - Target is not present in the array.
Examples
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Explanation: 0 is found at index 4 in the rotated array.
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Explanation: 3 is not present in the array.
Example 3:
Input: nums = [1], target = 0
Output: -1
Explanation: The array has only one element, and it's not the target.
Example 4:
Input: nums = [5,1,3], target = 5
Output: 0
Explanation: The target is the first element.
Constraints
1 <= nums.length <= 5000-1000 <= nums[i] <= 1000All the integers in nums are unique.-1000 <= target <= 1000- The time complexity should be O(log n).
Notes
Consider using a modified binary search approach. The key is to determine which half of the array is sorted and then decide which half to search based on the target value and the values at the midpoints. Think about how the rotation affects the sorted nature of the array's segments. You'll need to handle cases where the left and right subarrays are both sorted, and cases where only one is sorted. The pivot point is the index where the rotation occurred.