Search in Rotated Sorted Array II

Pattern: Binary search on rotated arrays

medium

The same search as before, but with repeated values. When nums[lo], nums[mid] and nums[hi] are all equal you cannot tell which half is sorted, so drop both ends and try again.

The problem

A sorted array, which may contain repeated values, was rotated at an unknown point. Given the rotated array and a target, return whether the target is in it. For example, [2, 5, 6, 0, 0, 1, 2] gives true for 0 and false for 3.

The function name search matches LeetCode. Use the link above for the exact statement and limits. Here the answer is true or false, not an index.

Think first

  • In Search in Rotated Sorted Array, which comparison found the sorted half?
  • With repeats, can nums[lo] == nums[mid] happen when the left half is not sorted?
  • When you cannot decide, what is a safe small step?

Hints

    Brute force, and why it fails

    Scan for the target: O(n). That is also the worst case of the method below, for arrays like [1, 1, 1, 1, 2, 1, 1]. On most inputs it still halves the range.

    The key insight

    Repeats only hurt when the three probed values are equal. In that case removing the two equal ends loses nothing, so the search goes on safely, just more slowly.

    Dry run

    10lo
    01 
    12 
    13 
    14hi

    nums = [1, 0, 1, 1, 1] and target = 0. The fall is between index 0 and 1, but the ends hide that.

    Step 1 of 4

    The plan

    lo = 0, hi = n - 1
    while lo <= hi:
        mid = lo + (hi - lo) / 2
        if nums[mid] == target: return true
        if nums[lo] == nums[mid] and nums[mid] == nums[hi]:
            lo = lo + 1; hi = hi - 1
        else if nums[lo] <= nums[mid]:
            if nums[lo] <= target < nums[mid]: hi = mid - 1
            else: lo = mid + 1
        else:
            if nums[mid] < target <= nums[hi]: lo = mid + 1
            else: hi = mid - 1
    return false
    

    Complexity

    Time
    O(log n) usually, O(n) worst
    Space
    O(1)

    When the three values keep being equal, each step removes only two values, so the worst case is O(n).

    Edge cases

    • All values equal and not the target: the ends shrink until the range is empty.
    • One value: compare it directly.
    • [3, 1, 1] with target 3: the right half is sorted, 3 is not in it, so the left part is searched.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean search(int[] nums, int target) {
            int lo = 0, hi = nums.length - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] == target) return true;
                if (nums[lo] == nums[mid] && nums[mid] == nums[hi]) {   // cannot tell which half is sorted
                    lo++;
                    hi--;
                } else if (nums[lo] <= nums[mid]) {                     // left half is sorted
                    if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
                    else lo = mid + 1;
                } else {                                                // right half is sorted
                    if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
                    else hi = mid - 1;
                }
            }
            return false;
        }
    }

    C++

    class Solution {
    public:
        bool search(vector<int>& nums, int target) {
            int lo = 0, hi = static_cast<int>(nums.size()) - 1;
            while (lo <= hi) {
                int mid = lo + (hi - lo) / 2;
                if (nums[mid] == target) return true;
                if (nums[lo] == nums[mid] && nums[mid] == nums[hi]) {   // cannot tell which half is sorted
                    lo++;
                    hi--;
                } else if (nums[lo] <= nums[mid]) {                     // left half is sorted
                    if (nums[lo] <= target && target < nums[mid]) hi = mid - 1;
                    else lo = mid + 1;
                } else {                                                // right half is sorted
                    if (nums[mid] < target && target <= nums[hi]) lo = mid + 1;
                    else hi = mid - 1;
                }
            }
            return false;
        }
    };

    Python

    class Solution:
        def search(self, nums: list[int], target: int) -> bool:
            lo, hi = 0, len(nums) - 1
            while lo <= hi:
                mid = (lo + hi) // 2
                if nums[mid] == target:
                    return True
                if nums[lo] == nums[mid] == nums[hi]:   # cannot tell which half is sorted
                    lo += 1
                    hi -= 1
                elif nums[lo] <= nums[mid]:             # left half is sorted
                    if nums[lo] <= target < nums[mid]:
                        hi = mid - 1
                    else:
                        lo = mid + 1
                else:                                   # right half is sorted
                    if nums[mid] < target <= nums[hi]:
                        lo = mid + 1
                    else:
                        hi = mid - 1
            return False

    Common mistakes

    • Using the first version unchanged, which fails on [1, 0, 1, 1, 1].
    • Checking the three-equal case after the sorted-half test, so the wrong half is trusted first.
    • Expecting O(log n) in every case. With repeats, no method can promise that.

    Similar problems