LC 33 - Search in Rotated Sorted Array
Question
There is an integer array nums sorted in ascending order (with distinct values).
Prior to being passed to your function, nums is possibly left rotated at an unknown index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be left rotated by 3 indices and become [4,5,6,7,0,1,2].
Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
1
2
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
1
2
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
Example 3:
1
2
Input: nums = [1], target = 0
Output: -1
Constraints:
1 <= nums.length <= 5000-104 <= nums[i] <= 104- All values of
numsare unique. numsis an ascending array that is possibly rotated.-104 <= target <= 104
Links
Question here and solution here
Solution
concept
This question is very similar to [[153. Find Minimum in Rotated Sorted Array]] where we consider 2 sorted portion. Basically once we determined which portion our current mid is in, we then determine search left and right depending on the conditions. Take note that for each portion, there is a case we need to determine search left or right (depend on the l and r boundary and whether they are smaller and bigger than the target) due to the rotation and left elements is always greater than right elements.
code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def search(self, nums: List[int], target: int) -> int:
l, r = 0, len(nums) - 1
while l <= r:
mid = (l + r) // 2
if nums[mid] == target:
return mid
# Left portion sorted
if nums[l] <= nums[mid]:
if nums[l] <= target < nums[mid]:
r = mid - 1
else:
l = mid + 1
# Right portion sorted
else:
if nums[mid] < target <= nums[r]:
l = mid + 1
else:
r = mid - 1
return -1
Complexity
time: $O(\log n)$ space: $O(1)$