Search in Rotated Sorted Array II (LeetCode 81): Solution and Explanation
A sorted array with repeated values has been rotated, and we need to say whether a target is present. Binary search still works: at each mid one side is usually a clean sorted run we can range-check. The only new case is when nums[lo], nums[mid] and nums[hi] are all equal, where we cannot tell which side is sorted and simply trim one value from each end.
Intuition
A rotated sorted array is two sorted runs placed back to back. Any mid splits the window so that at least one side lies entirely inside one run, and that side is sorted.
On a sorted side the question 'could the target be here?' is answered by comparing against its two end values. If yes we keep that side, otherwise we keep the other one.
Duplicates break the test for which side is sorted when the left end, the middle and the right end all hold the same value. In that case both ends are not the target (we already checked mid), so dropping them is safe and loses nothing.
Approach: Binary search with an end-trimming fallback
- Set lo = 0 and hi = n - 1.
- While lo <= hi, compute mid. If nums[mid] equals the target, return true.
- If nums[lo] == nums[mid] == nums[hi], increment lo and decrement hi and continue.
- Else if nums[lo] <= nums[mid], the left side is sorted: if nums[lo] <= target < nums[mid] set hi = mid - 1, otherwise set lo = mid + 1.
- Else the right side is sorted: if nums[mid] < target <= nums[hi] set lo = mid + 1, otherwise set hi = mid - 1.
- If the loop ends, return false.
Step-by-step example
nums = [1,0,1,1,1], target = 0
- lo = 0, hi = 4, mid = 2. nums[2] = 1 is not 0.
- nums[0], nums[2] and nums[4] are all 1, so we cannot tell where the drop is. Trim: lo = 1, hi = 3.
- mid = 2 again, nums[2] = 1. Now nums[lo] = 0 < nums[mid] = 1, so the left side [1..2] is sorted.
- 0 <= 0 < 1, so the target is in the left side: hi = 1.
- mid = 1, nums[1] = 0 equals the target. Return true.
Code: Python, Java, C++
1class Solution:
2 def search(self, nums: List[int], target: int) -> bool:
3 lo, hi = 0, len(nums) - 1
4 while lo <= hi:
5 mid = (lo + hi) // 2
6 if nums[mid] == target:
7 return True
8 if nums[lo] == nums[mid] == nums[hi]:
9 lo += 1
10 hi -= 1
11 elif nums[lo] <= nums[mid]:
12 if nums[lo] <= target < nums[mid]:
13 hi = mid - 1
14 else:
15 lo = mid + 1
16 else:
17 if nums[mid] < target <= nums[hi]:
18 lo = mid + 1
19 else:
20 hi = mid - 1
21 return False1class Solution {
2 public boolean search(int[] nums, int target) {
3 int lo = 0, hi = nums.length - 1;
4 while (lo <= hi) {
5 int mid = lo + (hi - lo) / 2;
6 if (nums[mid] == target) return true;
7 if (nums[lo] == nums[mid] && nums[mid] == nums[hi]) {
8 lo++;
9 hi--;
10 } else if (nums[lo] <= nums[mid]) {
11 if (nums[lo] <= target && target < nums[mid]) {
12 hi = mid - 1;
13 } else {
14 lo = mid + 1;
15 }
16 } else {
17 if (nums[mid] < target && target <= nums[hi]) {
18 lo = mid + 1;
19 } else {
20 hi = mid - 1;
21 }
22 }
23 }
24 return false;
25 }
26}1class Solution {
2public:
3 bool search(vector<int>& nums, int target) {
4 int lo = 0, hi = (int)nums.size() - 1;
5 while (lo <= hi) {
6 int mid = lo + (hi - lo) / 2;
7 if (nums[mid] == target) return true;
8 if (nums[lo] == nums[mid] && nums[mid] == nums[hi]) {
9 lo++;
10 hi--;
11 } else if (nums[lo] <= nums[mid]) {
12 if (nums[lo] <= target && target < nums[mid]) {
13 hi = mid - 1;
14 } else {
15 lo = mid + 1;
16 }
17 } else {
18 if (nums[mid] < target && target <= nums[hi]) {
19 lo = mid + 1;
20 } else {
21 hi = mid - 1;
22 }
23 }
24 }
25 return false;
26 }
27};Time and space complexity
O(log n) typical, O(n) worst case
Each round normally halves the window. When the three probes are equal we only remove two elements, so an array like [1,1,1,...,1,2,1,1] can force about n/2 rounds.
O(1)
Only the three indices lo, mid and hi are stored.
Other approaches
Linear scan (time O(n), space O(1))
Check every element. Simple and has the same worst case as the binary search, but never benefits from the sorted structure.
Find the pivot, then binary search one run (time O(n) worst case, space O(1))
Locate the rotation point first and search the run that can contain the target. With duplicates, finding the pivot also degrades to O(n) and needs two passes.
Common mistakes
- Using only nums[lo] <= nums[mid] to decide the sorted side. With duplicates, [1,0,1,1,1] would wrongly treat the left side as sorted and skip the 0.
- Trimming only one end. Shrinking lo alone also works but the symmetric trim is easier to reason about; either way, only trim after confirming nums[mid] is not the target.
- Mixing strict and non-strict comparisons in the range checks. The sorted left side covers [nums[lo], nums[mid]) and the sorted right side covers (nums[mid], nums[hi]], because mid itself was already checked.
Frequently asked questions
Why can this not always run in O(log n)?
When most values are equal, the probes at lo, mid and hi can look identical whether the odd value is on the left or the right. No comparison-based method can tell them apart without looking at more elements, so the worst case is linear.
How is this different from LeetCode 33?
Problem 33 has distinct values, so nums[lo] <= nums[mid] always identifies the sorted side. Here duplicates add the ambiguous case where the ends equal the middle, and we handle it by trimming.
Is it safe to drop nums[lo] and nums[hi] in the ambiguous case?
Yes. Both equal nums[mid], and we just checked that nums[mid] is not the target, so neither end can be the answer.
Does the function need to return the index?
No. This version only returns whether the target exists, which is why duplicates do not create any choice about which copy to report.