Home

153. Find Minimum in Rotated Sorted Array

We can perform a modified version of binary search in order to find the minimum element.

See code below for the different cases that we may encounter.

class Solution {
    public int findMin(int[] nums) {
        if (nums.length < 2) return nums[0];
        
        return search(nums, 0, nums.length - 1);   
    }
    
    public int search(int[] nums, int leftIndex, int rightIndex) {
        if (leftIndex >= rightIndex) return nums[leftIndex];
        
        int left = nums[leftIndex];
        int right = nums[rightIndex];
        
        /*
         *     x
         *    x
         *   x
         *  x
         * x
         */
        if (right > left) {
            return left;
        }
        
        
        //left > right
        int middleIndex = leftIndex + (rightIndex - leftIndex) / 2;
        int middle = nums[middleIndex];
        
        
        /*
         *  x
         * x
         *     x
         *    x
         *   x
         */
        if (left > middle) {
            return search(nums, leftIndex + 1, middleIndex);
        }
        
        /*
         *    x
         *   x
         *  x
         * x
         *     x
         */ 
        return search(nums, middleIndex + 1, rightIndex);
        
    }
}


Questions? Have a neat solution? Comment below!