You are given a sorted integer array nums
with distinct values that has been possibly rotated at an unknown pivot index k
(where 1 <= k < nums.length
). The rotated array looks like this: [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]
(0-indexed).
For example, the array [0, 1, 2, 4, 5, 6, 7]
might be rotated at pivot index 3
to become [4, 5, 6, 7, 0, 1, 2]
.
Given the rotated array nums
and an integer target
, your task is to return the index of target
if it is found in nums
, or -1
if it is not present.
Important Requirement: Your solution must have a runtime complexity of O(log n)
.
nums = [4,5,6,7,0,1,2], target = 0
Output: 4
nums = [4,5,6,7,0,1,2], target = 3
Output: -1
nums = [1], target = 0
Output: -1
1 <= nums.length <= 5000
-10^4 <= nums[i] <= 10^4
nums
are unique.nums
is an ascending array that is possibly rotated.-10^4 <= target <= 10^4
## Optimal Solution: Binary Search
This problem can be solved efficiently using a modified binary search algorithm. The key idea is to adapt the binary search to handle the rotated nature of the array.
```python
def search_rotated_array(nums, target):
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
left
to 0 and right
to the last index of the array.left
is less than or equal to right
.mid
.nums[mid]
equals the target
, return mid
.nums[left]
to nums[mid]
) is sorted.
target
lies within this sorted range. If it does, update right
to mid - 1
; otherwise, update left
to mid + 1
.target
lies within this sorted range. If it does, update left
to mid + 1
; otherwise, update right
to mid - 1
.target
, return -1.nums = [4, 5, 6, 7, 0, 1, 2]
target = 0
print(search_rotated_array(nums, target)) # Output: 4
The algorithm uses binary search, which divides the search space in half with each iteration. Therefore, the time complexity is O(log n), where n is the number of elements in the array.
The algorithm uses a constant amount of extra space for variables like left
, right
, and mid
. Thus, the space complexity is O(1).
nums
is empty, the algorithm should return -1.