Start learning free

LESSON 100 OF 314 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in Java: Binary Search, O(log n)

Practice O(log n) Read the full explanation

You get an array nums of different integers.

Return the smallest number in nums.

The numbers were sorted from smallest to largest. Then the array may have been rotated. A rotation moves the first k numbers to the end, in the same order. Here 0 <= k < nums.length.

For example, [1,4,6,9] with k = 1 becomes [4,6,9,1]. With k = 0, nothing moves.

 

Example 1:

Input: nums = [21,30,4,9,16]
Output: 4
Explanation: The sorted array was rotated with k = 3.
So 4, 9 and 16 moved to the end.
The smallest number is 4.

Example 2:

Input: nums = [-6,-2,5,12]
Output: -6
Explanation: This array was not rotated (k = 0).
The first number is the smallest.

Example 3:

Input: nums = [40,-5]
Output: -5

 

Constraints:

  • 1 to 1,000,000 numbers.
  • All numbers are different.
  • Each number is from -109 to 109.
  • The array is sorted, then maybe rotated (see above).

Note:

Your algorithm should run in O(log n) time and use O(1) extra space.

STEP 1 OF 6
    Ctrl + Enter to check

    JAVA · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Java, explained

    Problem overview

    The method findMin receives an int[] nums of distinct integers. The array was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end, with 0 <= k < nums.length. The method returns the smallest element, in O(log n) time and O(1) extra space.

    For [3, 4, 5, 1, 2] the answer is 1: the original array was [1, 2, 3, 4, 5], rotated at k = 2. For [4, 5, 6, 7, 0, 1, 2] it is 0. For [11, 13, 15, 17], which was not rotated, it is the first element, 11.

    Approach: compare the middle with the last element

    Scanning every element finds the minimum in O(n). To get O(log n), use binary search, even though the array is not sorted as a whole. A rotated array rises, drops once at the rotation point, and rises again. The minimum is the element right after the drop, or the first element if there was no rotation.

    The decision at each step is a single comparison, nums[middle] against nums[right]:

    • If nums[middle] > nums[right], the values drop somewhere between them. In a sorted stretch every value is smaller than the last one, so a middle value bigger than the last value means the rotation point lies after middle. The minimum is to the right, and middle itself cannot be it.
    • Otherwise nums[middle] < nums[right] (the values are distinct), so everything from middle to right is sorted. The minimum is at middle or to its left.

    The comparison is with the right end, not the left. Comparing with nums[left] fails for an array that was not rotated: nums[middle] is bigger than nums[left], yet the minimum is on the left.

    Trace for [4, 5, 6, 7, 0, 1, 2]:

    leftrightmiddlenums[middle]nums[right]Move
    063727 > 2, so left = 4
    465121 < 2, so right = 5
    454010 < 1, so right = 4

    Now left and right are both 4, the loop ends, and nums[4] is 0. For the unrotated [11, 13, 15, 17] every comparison goes to the else branch, and right moves down to 0, so the result is nums[0], which is 11.

    The invariant that makes this work is simple: after every pass, the minimum is still somewhere between left and right, inclusive. Both moves keep it inside, and both shrink the window, so the loop must end with a single index left.

    Step by step

    1. Set the window. left = 0 and right = nums.length - 1. The minimum can be anywhere, so the window is the whole array.
    2. Loop while left < right. It stops when the window is a single index, and that index holds the minimum. This is <, not <=.
    3. Find the middle. middle = left + (right - left) / 2. Integer division rounds down, so middle is always less than right while left < right.
    4. The key line. If nums[middle] > nums[right], set left = middle + 1. The value at middle is bigger than another element, so it cannot be the minimum, and it is safe to skip past it.
    5. Otherwise set right = middle, not middle - 1, because nums[middle] may itself be the minimum.
    6. Return nums[left]. Every pass kept the minimum inside the window, and the window is now one index.

    The solution in Java

    class Solution {
        public int findMin(int[] nums) {
            int left = 0, right = nums.length - 1;
            while (left < right) {
                int middle = left + (right - left) / 2;
                if (nums[middle] > nums[right]) {
                    left = middle + 1;
                } else {
                    right = middle;
                }
            }
            return nums[left];
        }
    }
    

    The Java details worth a closer look:

    • The result is a value, not an index. The method returns nums[left], an int. Returning left would give the position of the minimum, which is a different answer.
    • Integer division. (right - left) / 2 drops the fraction. For a window of two indices, middle is left. That is why left = middle + 1 always makes progress, and why right = middle does too: middle is strictly less than right whenever left < right.
    • left + (right - left) / 2 against (left + right) / 2. Java int arithmetic wraps silently on overflow, so adding two large indices can go negative. The subtraction form cannot overflow. Arrays here hold at most a million elements, so either form would work, but the safe one is the better habit.
    • Declaring two ints at once. int left = 0, right = nums.length - 1; is one statement.

    Complexity

    Time: O(log n). Each pass discards at least half of the window, either by moving left past middle or by pulling right back to middle.

    Space: O(1). The method uses only left, right and middle.

    Edge cases and common mistakes

    • One element. [7] returns 7: left equals right, the loop never runs, and nums[0] is returned.
    • Two elements. [2, 1] returns 1 and [1, 2] returns 1. For [2, 1], middle is 0, and 2 > 1 moves left to 1.
    • No rotation. [11, 13, 15, 17] returns 11. The array is sorted, so the minimum is the first element.
    • Comparing with nums[left]. A version that moves left when nums[middle] >= nums[left] returns 17 for [11, 13, 15, 17] and 2 for [4, 5, 6, 7, 0, 1, 2]. Both are wrong.
    • right = middle - 1. This can skip the minimum when middle is the minimum itself, as in the last step of the trace above.
    • Looping with left <= right. With right = middle, a window of one index would never shrink, and the loop would not end.
    • Duplicates. The method assumes distinct values. With repeats, nums[middle] == nums[right] would no longer say which side the minimum is on. The statement rules duplicates out.

    Testing

    • [3, 4, 5, 1, 2] gives 1.
    • [4, 5, 6, 7, 0, 1, 2] gives 0.
    • [11, 13, 15, 17] gives 11.
    • [7] gives 7.
    • [2, 1] gives 1.
    • [1, 2] gives 1.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free