#81
Search in Rotated Sorted Array II
MediumArrayBinary SearchBinary SearchArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a modified binary search allows us to efficiently locate the target in a rotated sorted array, even with duplicates. This approach reduces the number of comparisons significantly compared to brute force.
⚙️
Algorithm
6 steps- 1Step 1: Initialize two pointers, left and right, to the start and end of the array.
- 2Step 2: While left is less than or equal to right, calculate the mid index.
- 3Step 3: Check if nums[mid] equals the target; if so, return true.
- 4Step 4: If nums[left] is equal to nums[mid], increment left to skip duplicates.
- 5Step 5: Determine which side is sorted. If the left side is sorted and target lies within that range, move right; otherwise, move left.
- 6Step 6: If the right side is sorted and target lies within that range, move left; otherwise, move right.
solution.py21 lines
1# Full working Python code
2
3def search(nums, target):
4 left, right = 0, len(nums) - 1
5 while left <= right:
6 mid = (left + right) // 2
7 if nums[mid] == target:
8 return True
9 if nums[left] == nums[mid]:
10 left += 1
11 elif nums[left] <= nums[mid]:
12 if nums[left] <= target < nums[mid]:
13 right = mid - 1
14 else:
15 left = mid + 1
16 else:
17 if nums[mid] < target <= nums[right]:
18 left = mid + 1
19 else:
20 right = mid - 1
21 return Falseℹ
Complexity note: This complexity is due to the worst-case scenario where we might have to check every element in the array, especially when duplicates are present.
- 1Understanding how rotation affects the sorted order is crucial.
- 2Identifying duplicates can complicate the search process.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.