Search in Rotated Sorted Array II (Duplicates)

Find out whether a value is in a sorted array that was rotated and may contain repeated numbers.

Given an array of integers nums and a number target, return true if target is in nums and false if it is not. The array was first sorted so that each number is at least as large as the one before it, which means equal numbers may repeat. Then it was rotated: some numbers from the end were moved, in the same order, to the front. For example, [0, 0, 1, 2, 2, 5, 6] with its last three numbers moved to the front becomes [2, 5, 6, 0, 0, 1, 2]. You do not know how many numbers were moved.

Example 1
Input: nums = [2, 5, 6, 0, 0, 1, 2], target = 0
Output: true
Example 2
Input: nums = [2, 5, 6, 0, 0, 1, 2], target = 3
Output: false
Solution

The Idea

Imagine a row of number cards laid out from smallest to largest: 0, 0, 1, 2, 2, 5, 6. Someone takes the last three cards, 2, 5 and 6, and puts them at the front without changing their order. The row now reads 2, 5, 6, 0, 0, 1, 2, which is the array in both examples. Is there a 0 in it? Is there a 3?

Reading every card answers both questions, but it ignores the order the cards still have. For a row that is fully sorted, the usual way to search is binary search: look at the middle card and throw away the half that cannot hold the target. That works because everything left of the middle is smaller or equal, and everything right of it is larger or equal. Each look halves the cards left, so a million cards need only about 20 looks.

The rotated row is not sorted as a whole, but it is made of two sorted runs: 2, 5, 6, and then 0, 0, 1, 2. Mark the two ends of the part still being searched with lo and hi, and its middle with mid. The middle splits that part into a left half and a right half. The drop between the runs, from 6 to 0, falls in at most one of them, so at least one half is sorted from end to end.

When all numbers are different, comparing nums[lo] with nums[mid] tells which half that is, and the end values of the sorted half show at a glance whether the target can be inside it. That is how Search in Rotated Sorted Array works, for arrays without repeats. Repeats spoil the comparison. Look at the picture below.

Two arrays, [1, 0, 1, 1, 1] and [1, 1, 1, 0, 1]. In both, lo at position 0, mid at position 2 and hi at position 4 all read 1, but the 0 is in the left half of the first array and in the right half of the second.

In the top row, [1, 0, 1, 1, 1], lo is on position 0, mid on position 2 and hi on position 4, and all three read 1. The 0 is in the left half, so the left half, 1, 0, 1, is not sorted. The bottom row, [1, 1, 1, 0, 1], gives the same three 1s, but its 0 is in the right half. From those three values alone, the two rows look the same. So which half should the search keep?

It does not have to choose. If nums[mid] is not the target, then nums[lo] and nums[hi], which hold the same value as nums[mid], are not the target either. Both ends can go: move lo one step right and hi one step left, and look again. The part being searched shrinks by only two numbers instead of by half, but nothing that could be the target is lost.

Solution Approach

Turning that idea into code means settling three things: how to tell which half is sorted, how to decide which half to keep, and what to do when the three values match.

Telling which half is sorted

How does the code know which half has no drop? In a rotated array, every number in the second run is at most every number in the first run. In Example 1, the second run 0, 0, 1, 2 sits at or below 2, 5, 6. So if nums[mid] is larger than nums[lo], no drop can lie between them, and the left half is sorted. If nums[mid] is smaller, the drop is in the left half, so the right half is sorted.

Equal values are the hard case. When nums[lo] equals nums[mid] but nums[hi] is different, the left half is still sorted. A drop in the left half would put mid and hi in the second run, where values rise from nums[mid] to nums[hi] yet never go above nums[lo]. That would force nums[hi] to the same value. So nums[lo] <= nums[mid] means "left half sorted", unless all three values are equal.

Choosing the half to keep

Once one half is known to be sorted, can the target be inside it? A sorted left half holds the target only if nums[lo] <= target < nums[mid]. The upper bound is strict because nums[mid] was already compared with the target. If the target is in range, hi moves to mid - 1; if not, it can only be in the right half, and lo moves to mid + 1. A sorted right half works the same way, with nums[mid] < target <= nums[hi].

Take target 3 in Example 2. At the start, lo is 0, hi is 6 and mid is 3, holding 2, 2 and 0. Since nums[mid], 0, is smaller than nums[lo], 2, the right half 0, 0, 1, 2 is sorted. 3 is not between 0 and 2, so hi moves to 2, and only 2, 5, 6 are left to search.

When the three values match

What if nums[lo], nums[mid] and nums[hi] are all equal and nums[mid] is not the target? Then lo goes up by one and hi down by one. Neither end can be the target, since both hold the same value as nums[mid]. Follow the top row, [1, 0, 1, 1, 1], with target 0. The first look sees three 1s, so lo becomes 1 and hi becomes 3.

Now nums[lo] is 0 and nums[mid] and nums[hi] are 1. The left half, 0, 1, is sorted and its range holds 0, so hi becomes 1. The next look lands on position 1, which holds the 0.

Java Solution

The method search works in these steps:

  1. First, set lo to 0 and hi to the last position, nums.length - 1. Together they mark the part of the array still being searched.
  2. Loop while lo <= hi. In each round, set mid to the middle position, lo + (hi - lo) / 2. Written this way, no step goes past the largest int value, which lo + hi could do on a huge array.
  3. If nums[mid] equals target, return true.
  4. If nums[lo], nums[mid] and nums[hi] are all equal, add 1 to lo, take 1 from hi, and go on to the next round.
  5. Otherwise, if nums[lo] <= nums[mid], the left half is sorted. Keep it with hi = mid - 1 when the target is in its range, or move to the right half with lo = mid + 1.
  6. Otherwise the right half is sorted, and the same check uses nums[mid] and nums[hi].
  7. When lo passes hi, nothing is left to search, so return false.

The main method runs both examples, the two rows of the picture with target 0, an array of only 1s searched for 2, and an array holding the single number 4.

Java
public class SearchInRotatedSortedArrayII {

    public static boolean search(int[] nums, int target) {
        int lo = 0;
        int 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]) {
                lo++;                                // cannot tell which half is sorted:
                hi--;                                // drop both ends and try again
            } 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;
    }

    public static void main(String[] args) {
        int[] nums = {2, 5, 6, 0, 0, 1, 2};
        System.out.println(search(nums, 0));
        System.out.println(search(nums, 3));
        System.out.println(search(new int[] {1, 0, 1, 1, 1}, 0));
        System.out.println(search(new int[] {1, 1, 1, 0, 1}, 0));
        System.out.println(search(new int[] {1, 1, 1}, 2));
        System.out.println(search(new int[] {4}, 4));
    }
}

Running it prints:

Output
true
false
true
true
false
true

Look at the top two lines: 0 is found in [2, 5, 6, 0, 0, 1, 2] and 3 is not. Finding the 0 takes a single look, because mid starts on position 3, which holds a 0.

The third and fourth lines, both true, are the two rows of the picture, and the third one depends on the branch for three equal values. Without that branch, the code calls the left half 1, 0, 1 sorted, decides 0 cannot lie between 1 and 1, and moves lo past the 0. That version prints false for [1, 0, 1, 1, 1]. It still prints true for [1, 1, 1, 0, 1], only because its 0 happens to sit in the half that version keeps.

The fifth line, false, comes from [1, 1, 1] with target 2. Every look sees three equal values, so lo and hi close in from both ends until nothing is left. The last line shows that an array of one number finds that number.

Complexity

The cost depends on how often a look can throw away half the range, and how often it can only drop the two ends.

  • Time: O(log n) when the three values rarely match, O(n) in the worst case. A look that finds a sorted half halves the n numbers left, as plain binary search does. But in an array of many 1s with a single 0, almost every look sees three 1s and removes only two numbers. No method can do better there, because the 0 could be at any position not yet looked at.
  • Space: O(1), because the search keeps only lo, mid and hi, however many rounds it takes.