You are given a rotated sorted array nums
and a target value. The array was initially sorted in ascending order, but it has been rotated at some unknown pivot index k
. Your task is to find the index of the target
in the rotated array. If the target
is not found, return -1. You must write an algorithm with O(log n) runtime complexity.
Constraints:
nums.length
<= 5000nums[i]
<= 104nums
are unique.nums
is an ascending array that is possibly rotated.target
<= 104Examples:
nums
= [4, 5, 6, 7, 0, 1, 2], target
= 0
Output: 4nums
= [4, 5, 6, 7, 0, 1, 2], target
= 3
Output: -1nums
= [1], target
= 0
Output: -1Explain your approach and provide the code. Also, analyze time and space complexity. How would you handle the edge cases?
The most straightforward solution is to iterate through the array nums
and check if each element is equal to the target
. If we find the target
, we return its index. If we reach the end of the array without finding the target
, we return -1.
def search_naive(nums, target):
for i in range(len(nums)):
if nums[i] == target:
return i
return -1
The time complexity of this naive solution is O(n), where n is the length of the array nums
, because, in the worst case, we have to iterate through the entire array.
The space complexity is O(1) because we are only using a constant amount of extra space.
Since the array is sorted (and rotated), we can use a modified binary search to find the target in O(log n) time. The idea is to first find the pivot (the index of the smallest element in the array), and then perform binary search in the appropriate half of the array.
target
is equal to the element at the pivot, return the pivot index.target
is greater than or equal to the first element of the array, search in the first half of the array (from index 0 to pivot - 1).def search(nums, target):
if not nums:
return -1
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
# Check if the left side is sorted
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
# Otherwise, the right side is sorted
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
The time complexity of the optimal solution is O(log n), where n is the length of the array nums
. This is because we are using binary search to find both the pivot and the target.
The space complexity is O(1) because we are only using a constant amount of extra space.
nums
is empty, return -1.