Find Minimum in Rotated Sorted Array II (Duplicates)

Find the smallest value in a sorted array that was rotated and may hold the same value more than once.

An array of integers was sorted in ascending order and then rotated: some of its first values, possibly none, were moved to its end in the same order. The array may hold the same value more than once. Given the rotated array nums, return its smallest value.

Example 1
Input: nums = [1, 3, 5]
Output: 1
Example 2
Input: nums = [2, 2, 2, 0, 1]
Output: 0
Solution

The Idea

Picture a row of number cards laid out in order: 0, 1, 2, 2, 2. Someone lifts the first two cards off the front and puts them at the back, so the row now reads 2, 2, 2, 0, 1. That is Example 2. The card we want is the 0, and it sits right where the order drops.

Reading the whole row and keeping the smallest card always works, but it looks at every card. A sorted array is usually searched faster by halving: look at the middle, decide which half holds the answer, and throw the other half away. Searching by halving like that is called binary search. Can a rotated row still be halved?

Keep two markers on the part of the array still in play: lo on its first position and hi on its last. Then look at mid, the position halfway between them, and compare its value with the value at hi.

In Example 2, mid is index 2, holding 2, and hi holds 1. The middle value is bigger than the last one, so the order must drop somewhere after mid, and the smallest value is to its right. Had the middle value been smaller than the last one, the stretch from mid to hi would climb steadily, and the smallest value would be at mid or to its left.

Repeated values raise a new question: what if the middle value and the last value are equal? Look at the picture below.

Two arrays, Row A 3, 3, 3, 1, 3 and Row B 3, 1, 3, 3, 3. In both, mid at index 2 and hi at index 4 hold 3, yet the minimum 1 is right of mid in Row A and left of mid in Row B. Dropping hi is safe because a 3 stays at mid.

In Row A, mid at index 2 and hi at index 4 both hold 3, and the 1 is right of mid, at index 3. In Row B, the same two positions hold the same two 3s, but the 1 is left of mid, at index 1. Comparing the middle with the end cannot tell these two rows apart.

So we cannot throw away half of the range. We can still throw away one value: the one at hi. Even if it were the smallest value, its copy at mid would stay in the range, so nothing is lost. That is the bottom line of the picture: drop hi, since a 3 stays at mid.

Solution Approach

Turning that idea into code means settling three things: what to compare the middle value with, how far to move a marker in each case, and what the equal case costs.

Comparing the middle with the end

Why compare with the last value and not the first? Take [1, 3, 5] and [3, 5, 1]. In both, the middle value is bigger than the first value, yet the smallest value is left of the middle in one and right of it in the other. Compared with the last value, 3 is smaller than 5 and 5 is bigger than 1, so the two arrays get different, correct answers.

Moving the markers

How far can each case move a marker? When nums[mid] > nums[hi], the value at mid is bigger than another value, so it cannot be the smallest, and lo jumps to mid + 1. When nums[mid] < nums[hi], the value at mid may be the smallest, so hi moves to mid and keeps it.

When the two are equal, hi moves back by one, as the picture showed. The search goes on while lo is left of hi. Once they meet, one position is left, and it holds the smallest value.

What the equal case costs

The equal case removes one value, not half the range. With all values different it never happens, and a sorted array of 1,000 values takes 10 passes. With many repeats it can be as slow as reading every value: for 1,000 values that are all 3 except a 1 at index 0, the loop runs 999 times.

No search can do better on such input. In an array of 3s with one 1 hidden in it, any position not yet looked at could be the 1.

Java Solution

The method findMin works in these steps:

  1. First, set lo to 0 and hi to the last index, nums.length - 1, so the whole array is in play.
  2. Loop while lo < hi. Inside, find the middle position mid with lo + (hi - lo) / 2, which rounds down, so mid is always left of hi.
  3. If nums[mid] > nums[hi], set lo = mid + 1. If nums[mid] < nums[hi], set hi = mid.
  4. Otherwise the two values are equal, so drop the last value with hi--.
  5. When lo and hi meet, return nums[lo].

The main method runs both examples, Row A and Row B from the picture, [3, 3, 1, 3], an array of one repeated value, and an array of a single value.

Java
import java.util.Arrays;

public class FindMinimumInRotatedSortedArrayII {

    public static int findMin(int[] nums) {
        int lo = 0;
        int hi = nums.length - 1;
        while (lo < hi) {
            int mid = lo + (hi - lo) / 2;
            if (nums[mid] > nums[hi]) {
                lo = mid + 1;        // minimum is to the right of mid
            } else if (nums[mid] < nums[hi]) {
                hi = mid;            // minimum is mid or to its left
            } else {
                hi--;                // equal: side unknown, but nums[hi] has a copy at mid
            }
        }
        return nums[lo];
    }

    public static void main(String[] args) {
        int[][] inputs = {
            {1, 3, 5},
            {2, 2, 2, 0, 1},
            {3, 3, 3, 1, 3},
            {3, 1, 3, 3, 3},
            {3, 3, 1, 3},
            {1, 1, 1},
            {7}
        };
        for (int[] nums : inputs) {
            System.out.println(Arrays.toString(nums) + " -> " + findMin(nums));
        }
    }
}

Running it prints:

Output
[1, 3, 5] -> 1
[2, 2, 2, 0, 1] -> 0
[3, 3, 3, 1, 3] -> 1
[3, 1, 3, 3, 3] -> 1
[3, 3, 1, 3] -> 1
[1, 1, 1] -> 1
[7] -> 7

Look at the lines for [3, 3, 3, 1, 3] and [3, 1, 3, 3, 3], Row A and Row B. Their first pass sees the same 3 at mid and hi, and both still find the 1 on opposite sides.

The line for [3, 3, 1, 3] prints 1 too. Its first pass has mid at index 1, a 3 equal to the 3 at hi, so hi drops to index 2. The next pass compares 3 with 1, moves lo to index 2, and the search ends on the 1. A version that sets hi = mid in the equal case keeps only indices 0 and 1 after the first pass, both 3, and returns 3 for this array.

For [1, 1, 1] every pass is the equal case, and hi steps back until it meets lo. For [7] the loop never runs, and the single value comes back as it is.

Complexity

The work is the number of passes of the loop, and each pass does one comparison and moves one marker.

  • Time: O(log n) when values are distinct, O(n) in the worst case. The bigger and smaller cases halve the range on each pass, but the equal case removes only one value, so an array of 3s with a 1 at index 0 takes n - 1 passes.
  • Space: O(1). However many passes the loop takes, it only updates lo, hi and mid.

When no value repeats, the equal case cannot happen and the search is always O(log n): see Find Minimum in Rotated Sorted Array.