Search in Rotated Sorted Array II
LeetCode 81 · Medium · solution, intuition & step-by-step walkthrough
nums[low] == nums[mid] == nums[high] ⇒ low++, high−−.
This is how I solved Search in Rotated Sorted Array II (LeetCode 81), a medium problem from the Rotated Sorted Array pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.
Approach
- 1
mid matches → True.
- 2
Ambiguous triple → shrink both ends.
- 3
Otherwise apply the sorted-half test.
- 4
Not found → False.
How I solved it
Binary search with duplicate shrinkPythonO(log n) avg
class Solution:
def search(self, nums: List[int], target: int) -> bool:
low = 0
high=len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==target:
return True
if nums[low]==nums[mid] and nums[mid]==nums[high]:
low = low+1
high= high-1
continue
if nums[low]<=nums[mid]:
#left half is sorted
if target>=nums[low] and target<nums[mid]:
high = mid-1
else:
low=mid+1
else:
if target>nums[mid] and target<=nums[high]:
low=mid+1
else:
high=mid-1
return FalseSearch in Rotated Sorted Array II — FAQ
What is the intuition behind Search in Rotated Sorted Array II?
Like the distinct version, but duplicates can hide which half is sorted (e.g. low, mid and high all equal). In that ambiguous case shrink both ends by one and retry.
How do you solve Search in Rotated Sorted Array II (LeetCode 81)?
1. mid matches → True. 2. Ambiguous triple → shrink both ends. 3. Otherwise apply the sorted-half test. 4. Not found → False.
What is the time and space complexity of Search in Rotated Sorted Array II?
Time: O(log n) average, O(n) worst. Space: O(1). (Accepted approach: Binary search with duplicate shrink.)
What are common mistakes in Search in Rotated Sorted Array II?
Duplicates make the worst case linear — that's unavoidable.