AlgoInsight

DSA problem

Search in Rotated Sorted Array II

MediumBinary SearchPattern: Binary Searchtop600AmazonMicrosoftGoogleFacebook

There is an integer array nums sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, nums is rotated at an unknown pivot index. Given the array nums after the rotation and an integer target, return true if target is in nums, or false otherwise.

This is the duplicate-tolerant cousin of the previous problem. With distinct values we could always identify which half is sorted by comparing nums[lo] to nums[mid]. Duplicates break that guarantee: if nums[lo] == nums[mid], both halves could equally well be sorted or contain the rotation pivot, so no decision can be made.

The fix is a single defensive step. When nums[lo] == nums[mid] and nums[mid] == nums[hi], you cannot tell which side is sorted; simply shrink the window from both ends with lo++ and hi-- and try again. In the worst case (an array like [1, 1, 1, 1, ..., 1]), this degrades to O(n). On average and in any input with a reasonable mix of values, the algorithm remains effectively O(log n).

Aside from that shrink step, the structure is identical to the distinct-values variant: identify which side is sorted, decide whether target could be inside that sorted half's range, and discard the other half. Return true immediately on any match.

Examples

Example 1
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
Explanation: The rotation pivot is between index 2 and 3. Standard rotated binary search finds 0 in the right half.
Example 2
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
Explanation: Following the same logic, 3 fits into none of the half ranges and the window shrinks until lo > hi.
Example 3
Input: nums = [1,0,1,1,1], target = 0
Output: true
Explanation: When nums[lo]=nums[mid]=nums[hi]=1, shrink both ends; eventually the search reveals the 0.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-searcharrayrotated-array

Browse all DSA problems