LeetCode – Find Minimum in Rotated Sorted Array II (Java)

Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed?

Would this affect the run-time complexity? How and why?

Java Solution 1 - Recursion

This is a follow-up problem of finding minimum element in rotated sorted array without duplicate elements. We only need to add one more condition, which checks if the left-most element and the right-most element are equal. If they are we can simply drop one of them. In my solution below, I drop the left element whenever the left-most equals to the right-most.

public int findMin(int[] num) {
    return findMin(num, 0, num.length-1);
public int findMin(int[] num, int left, int right){
        return num[left];
    if(right == left +1){
        return Math.min(num[left], num[right]);
    // 3 3 1 3 3 3
    int middle = (right-left)/2 + left;
    // already sorted
    if(num[right] > num[left]){
        return num[left];
    //right shift one
    }else if(num[right] == num[left]){
        return findMin(num, left+1, right);
    //go right    
    }else if(num[middle] >= num[left]){
        return findMin(num, middle, right);
    //go left    
        return findMin(num, left, middle);

Java Solution 2 - Iteration

public int findMin(int[] nums) {
    int i=0;
    int j=nums.length-1;
        //handle cases like [3, 1, 3]
        while(nums[i]==nums[j] && i!=j){
            return nums[i];
        int m=(i+j)/2;
    return -1;
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Khatri on 2015-10-8

    What is the time complexity for this method? I think in worst case it will O(n), Please correct me if I am wrong! Thank you.

  2. Khatri on 2015-10-8

    okay! got it. It is still O(log(n)).Right?

  3. Larry Okeke on 2016-3-24

    public static void solution(){

    arr = new int[] {6, 7, 8, 9, 1, 1, 2, 2, 3, 4, 5};

    int solut = recurse(0, 5, 9);

    log(solut+" ");


    public static int recurse(int l, int middle, int r){

    if(r - l <= 2) return (arr[l] < arr[r]) ? arr[l] : arr[r];

    if(arr[l] arr[l])

    return recurse(l, (middle/2)+1, middle);

    return recurse(middle, middle + middle/2, r) ;


  4. Larry Okeke on 2016-3-24

    If the worst case is an array of one number duplicated many times… I agree with you

Leave a comment