Start learning free

LESSON 378 OF 667 · BINARY SEARCH

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

Practice O(log n) Read the full explanation

You get a vector 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.size().

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

    C++ · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in C++, explained

    Problem overview

    The method findMin receives a vector<int> named nums of distinct integers. The vector was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end. For example, [0, 1, 2, 4, 5, 6, 7] rotated at k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. The method returns the smallest element.

    For [3, 4, 5, 1, 2] the answer is 1, and for [4, 5, 6, 7, 0, 1, 2] it is 0. For [11, 13, 15, 17], which was not rotated (k = 0), the answer is 11, the first element. The statement asks for O(log n) time and O(1) extra space, with up to a million elements.

    Approach: compare the middle with the last element

    Scanning the whole vector for the minimum is O(n). Rotation doesn't scramble the vector, though: it 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 is no drop. Binary search can find that point.

    At each step, compare the middle element with the last element of the window:

    • If nums[middle] > nums[right], the values must drop somewhere between middle and right. A sorted stretch ends with its largest value, so a middle that is bigger than the end can't be in one. The minimum is strictly to the right of middle.
    • Otherwise nums[middle] < nums[right] (the values are distinct, so they can only be equal when middle == right). Everything from middle to right is sorted, so the minimum is at middle or to its left.

    Each pass halves the window, and the minimum always stays inside it. When the window is a single index, that index holds the minimum.

    In [4, 5, 6, 7, 0, 1, 2], the middle element is 7 and the last is 2. Since 7 is bigger than 2, the drop lies after the middle, and so does the minimum.

    Step by step

    1. Declare left and right as ints on one line: 0 and nums.size() - 1. The minimum can be anywhere, so the window is the whole vector.
    2. Loop while left < right. This time the test is <, not <=: the loop stops when the window is one index, and that index is the answer.
    3. Compute middle as left + (right - left) / 2. Integer division rounds down, so middle is always less than right while the window has at least two elements.
    4. If nums[middle] > nums[right], set left = middle + 1. The middle element is bigger than another element, so it can't be the minimum, and it can be skipped.
    5. Otherwise set right = middle. Not middle - 1: nums[middle] may itself be the minimum.
    6. After the loop, return nums[left]. left and right have met.

    The solution in C++

    class Solution {
    public:
        int findMin(vector<int> &nums) {
            int left = 0, right = nums.size() - 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 C++ details worth knowing:

    • The loop must make progress. Because middle is rounded down, it is always less than right when left < right. So both updates shrink the window: left = middle + 1 moves left up, and right = middle moves right down. If the midpoint rounded up, right = middle could repeat forever.
    • Signed indices. nums.size() is unsigned, but right is an int holding nums.size() - 1. For a non-empty vector that is the last index. The constraints guarantee at least one element.
    • One declaration, two variables. int left = 0, right = nums.size() - 1; declares two ints with their own initial values.
    • The vector is passed by reference, so the up-to-a-million elements are not copied, and the function only reads them.

    Tracing the example

    With nums = [4, 5, 6, 7, 0, 1, 2], the windows are:

    leftrightmiddlenums[middle]nums[right]Action
    063727 is bigger, so left = 4
    465121 is smaller, so right = 5
    454010 is smaller, so right = 4

    Now left and right are both 4, the loop ends, and the function returns nums[4], which is 0.

    Complexity

    Time is O(log n). Each pass at least halves the window, and does one comparison.

    Extra space is O(1). Three integers, no recursion.

    Edge cases and common mistakes

    • Not rotated. [11, 13, 15, 17] returns 11. The middle is never bigger than the last element, so right keeps moving to middle until it reaches index 0.
    • One element. [1] returns 1 without entering the loop.
    • Two elements. [2, 1] returns 1 and [1, 2] returns 1. In [2, 1] the middle is index 0, the value 2 is bigger than the last element 1, so left becomes 1.
    • Comparing with nums[left] instead of nums[right]. In an unrotated vector the middle is always bigger than the first element, yet the minimum is on the left. A version that compares with nums[left] returns 15 for [11, 13, 15, 17] and 5 for [2, 3, 4, 5, 1], both wrong.
    • Writing right = middle - 1. This can discard the minimum when it sits at middle. For [3, 1, 2], the middle is 1, which is the minimum, and the version with middle - 1 returns 3.
    • Using left <= right. With right = middle as an update, this condition can loop forever when the window is one element, because right stops changing. The loop must use left < right.
    • Duplicates. The values are distinct here. With repeated values, nums[middle] == nums[right] no longer tells which side holds the minimum, and the search needs extra handling.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free