LeetCode #33: Search in Rotated Sorted Array
https://leetcode.com/problems/search-in-rotated-sorted-array/
To solve this problem in Python 3, we can use a modified binary search algorithm to search for the target element in the sorted rotated array.
Here are the steps to follow:
- Initialize two pointers,
left
andright
, to the first and last indices of the input arraynums
, respectively. - Perform binary search until the
left
pointer is equal to or greater than theright
pointer. - Calculate the
mid
index as the average ofleft
andright
. - If
nums[mid] == target
, returnmid
. - If
nums[left] <= nums[mid]
, the left half is sorted.- If
nums[left] <= target < nums[mid]
, the target is in the left half. Setright
tomid - 1
. - Otherwise, the target is in the right half. Set
left
tomid + 1
.
- If
- If
nums[mid] < nums[right]
, the right half is sorted.- If
nums[mid] < target <= nums[right]
, the target is in the right half. Setleft
tomid + 1
. - Otherwise, the target is in the left half. Set
right
tomid - 1
.
- If
Here’s the Python 3 code that implements this approach:
class Solution:
def search(self, nums: List[int], target: int) -> int:
left, right = 0, len(nums) - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
return mid
if nums[left] <= nums[mid]:
if nums[left] <= target < nums[mid]:
right = mid - 1
else:
left = mid + 1
else:
if nums[mid] < target <= nums[right]:
left = mid + 1
else:
right = mid - 1
return -1
In this code, we first initialize two pointers, left
and right
, to the first and last indices of the input array nums
, respectively. We then perform binary search by calculating the mid
index and comparing nums[mid]
to target
.
If nums[mid] == target
, we return mid
. Otherwise, we check if the left half or right half is sorted by comparing nums[left]
to nums[mid]
. Depending on whether the left half or right half is sorted, we check if the target is in that half of the array. We then update left
or right
accordingly and repeat the binary search until the target is found or the pointers left
and right
cross each other.
Finally, we return -1 if the target is not found in the input array.
Time and Space Complexity
The time complexity of the solution is O(log n) because it uses binary search to find the target element. In the worst case, the algorithm needs to search through half of the input array on each iteration, resulting in O(log n) time complexity.
The space complexity of the solution is O(1) because it only uses a constant amount of extra space to store the pointers left
, right
, and mid
. Thus, the space used does not depend on the size of the input array.