Search in Rotated Sorted Array II, with duplicates handled
Search in Rotated Sorted Array II asks whether a target exists in a sorted array that was rotated and may contain duplicates. The standard answer is binary search that first works out which half is sorted, and when the low, middle and high values are all equal, shrinks both ends by one. Average time is O(log n), but duplicates push the worst case to O(n).
By Evin JohnPublished 8 min read
Restating the task
Someone took a list sorted in non-decreasing order, cut it at an unknown point, and moved the front piece to the back. The list can contain repeated values. Given that list and a target, report whether the target appears anywhere. You only need a yes or no, not a position.
| Rotated list | Target | Result | What it shows |
|---|---|---|---|
| [5, 6, 6, 9, 1, 2, 2, 5] | 2 | true | The target sits in the wrapped tail |
| [5, 6, 6, 9, 1, 2, 2, 5] | 7 | false | Inside the overall range but absent |
| [4, 4, 4, 1, 4] | 1 | true | Ends and middle are equal, so halves look identical |
| [8, 8, 8, 8] | 3 | false | Every value repeated, no rotation visible |
| [3] | 3 | true | Single element |
This is the follow-up to the version with distinct values. In the distinct version, comparing the first and middle values always tells you which half is in order. Duplicates break that guarantee, and the whole question is really about how you handle it.
Baseline: read every element
A linear scan answers the question in O(n) time with no extra memory. It is not a throwaway: as you will see, the best possible worst case for this problem is also linear, so the scan is a fair benchmark. State it, give its cost, and then explain that binary search still wins on typical inputs where duplicates are few.
def contains_linear(arr, target):
for value in arr:
if value == target:
return True
return FalseBinary search that survives duplicates
Pick a middle index. In a rotated list, at least one of the two halves, [low, mid] or [mid, high], is in sorted order. If you know which one, you can test in constant time whether the target falls between that half's endpoints. If it does, search there. If it does not, it must be in the other half, if it is anywhere.
With distinct values, arr[low] <= arr[mid] proves the left half is sorted. With duplicates there is one ambiguous situation: arr[low], arr[mid] and arr[high] all equal. Look at [4, 4, 4, 1, 4] and [4, 1, 4, 4, 4]. The three probes read 4, 4, 4 in both, yet the dip is on different sides. No constant number of reads can settle that, so the safe move is to drop low and high (neither is the target, since arr[mid] was already checked) and try again.
- Check the middleIf
arr[mid]equals the target, return true. - Handle the tieIf the values at low, mid and high are all equal, move
lowup by one andhighdown by one, then loop. - Left half sortedOtherwise, if
arr[low] <= arr[mid], the left side is ordered. Ifarr[low] <= target < arr[mid], search left; else search right. - Right half sortedOtherwise the right side is ordered. If
arr[mid] < target <= arr[high], search right; else search left. - Give up when emptyWhen
lowpasseshigh, the target is not there. Return false.
Why is the left half sorted when arr[low] == arr[mid] but arr[high] differs? If the drop were inside the left half, the right half would be a sorted run that ends below the start of the list, which forces arr[low] >= arr[high] >= arr[mid] = arr[low], meaning all three are equal. That is exactly the tie case, which was already handled.
def contains_rotated(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return True
if arr[low] == arr[mid] == arr[high]:
low += 1
high -= 1
elif arr[low] <= arr[mid]:
if arr[low] <= target < arr[mid]:
high = mid - 1
else:
low = mid + 1
else:
if arr[mid] < target <= arr[high]:
low = mid + 1
else:
high = mid - 1
return Falsefunction containsRotated(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return true;
if (arr[low] === arr[mid] && arr[mid] === arr[high]) {
low++;
high--;
} else if (arr[low] <= arr[mid]) {
if (arr[low] <= target && target < arr[mid]) high = mid - 1;
else low = mid + 1;
} else {
if (arr[mid] < target && target <= arr[high]) low = mid + 1;
else high = mid - 1;
}
}
return false;
}A short trace
Search [5, 6, 6, 9, 1, 2, 2, 5] for 2. low is 0, high is 7, mid is 3 with value 9. The left side runs 5 to 9 in order, and 2 is not in [5, 9), so low becomes 4. Now mid is 5 with value 2, which matches. Two probes instead of eight reads. Now search [4, 4, 4, 1, 4] for 1: the first probe sees 4, 4, 4 at low, mid and high, so both ends shrink. With low 1 and high 3, mid is 2 with value 4; the left side [4, 4] counts as sorted and 1 is outside it, so low becomes 3, where the 1 is found.
Running time, honestly
| Version | Typical time | Worst-case time | Extra space |
|---|---|---|---|
| Linear scan | O(n) | O(n) | O(1) |
| Rotated binary search, distinct values | O(log n) | O(log n) | O(1) |
| Rotated binary search with duplicate trimming | O(log n) | O(n) | O(1) |
Picture a list made almost entirely of 7s with one 3 hidden somewhere. Every probe reads 7 at low, mid and high, so each round removes only two elements. No algorithm can do better in that case, because any element you skip could be the 3. When an interviewer asks why this version is not logarithmic, that example is the answer.
Inputs that break careless code
- Empty list:
highstarts at -1, the loop does not run, and the function returns false. - All values equal and the target absent, like [8, 8, 8, 8] with 3: the trimming runs until the window is empty.
- No rotation at all, such as [1, 2, 2, 3]: the left half is always sorted and the code acts like ordinary binary search.
- Target equal to the duplicated boundary value, like 4 in [4, 4, 1, 2, 4]: found on the first probe or after one trim.
- Two elements in either order: check that the bounds
low <= target < arr[mid]do not skip the last candidate.
Frequent errors
- Reusing the distinct-values code unchanged. It returns false on inputs like [1, 0, 1, 1, 1] with target 0, because
arr[low] <= arr[mid]wrongly claims the left half is sorted. - Finding the pivot first, then searching. Locating the rotation point with duplicates is itself O(n) in the worst case, and the code is longer. One combined pass is cleaner.
- Jumping past mid on a tie. Only
lowandhighare known not to hold the target. Settinglow = mid + 1because three values match skips the 1 in [4, 1, 4, 4, 4]. - Using strict and inclusive bounds the wrong way round. The sorted-half test must include the endpoint you did not already check and exclude
arr[mid]. - Claiming O(log n) without a caveat. The duplicate case is the point of this variant.
Fictional interview exchange
Fictional example
- Interviewer
- Your search looks logarithmic. Is it?
- Candidate
- Only when duplicates do not hide the rotation. If low, mid and high hold the same value, I cannot tell which half is sorted, so I trim both ends. A list of all 7s with one 3 forces that every round, which makes it linear.
- Candidate
- And no approach can beat that on such an input, because the odd value could be at any unread position.
Neighbors in this problem set
The companion problem, Find Minimum in Rotated Sorted Array II, uses the same tie-breaking idea to locate the smallest value instead of a target. If you want a cleaner logarithmic search first, Single Element in a Sorted Array has no duplicate trap. Nth Digit is a different flavor of narrowing down by ranges. The data structure interview questions page covers arrays in general.
Rehearsing with Natively
For practice, Natively can look at a screenshot of a coding prompt and propose a direction, so you can test your own reasoning against it once you have a draft. Because it transcribes mock sessions on your computer, you can replay whether you mentioned the duplicate worst case when an interviewer asked. See how an AI interview assistant fits into a practice routine.
Questions people ask
How is Search in Rotated Sorted Array II different from the first version?
The list may contain duplicates, and you return true or false instead of an index. Duplicates can make the first, middle and last values equal, which hides which half is sorted.
What do you do when arr[low], arr[mid] and arr[high] are equal?
Move low up by one and high down by one. Neither end can be the target because the middle was already checked and holds the same value, so nothing is lost.
What is the time complexity with duplicates?
O(log n) on typical inputs but O(n) in the worst case, for example a list of identical values with one different value hidden inside. No algorithm can avoid reading most of that list.
Can I find the rotation point first and then binary search?
You can, but finding the pivot with duplicates is also linear in the worst case and takes more code. A single pass that decides which half is sorted is the usual interview answer.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
