Start learning free

LESSON 100 OF 314 · BINARY SEARCH

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

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.len().

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

    RUST · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Rust, explained

    Problem overview

    The function find_min receives a vector of distinct integers, nums, that was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end. With k = 3, [0, 1, 2, 4, 5, 6, 7] becomes [4, 5, 6, 7, 0, 1, 2], and with k = 0 the vector stays as it was. The function returns the smallest element, in O(log n) time and O(1) space.

    For [3, 4, 5, 1, 2] the answer is 1, for [4, 5, 6, 7, 0, 1, 2] it is 0, and for the unrotated [11, 13, 15, 17] it is 11, the first element.

    Approach: compare the middle with the last element

    Scanning the vector takes O(n). For O(log n), use binary search on the window of indexes that can still hold the minimum, and decide at each step which half to discard.

    The minimum is the element where the values drop, the rotation point (or the first element if there was no rotation). Compare nums[middle] with 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 bigger middle means the rotation point lies to the right of middle. Also, nums[middle] is bigger than another element, so it can't be the minimum. Move left to middle + 1.
    • Otherwise nums[middle] < nums[right] (the values are distinct, so they are never equal when middle differs from right). Everything from middle to right is sorted, so the minimum of that stretch is nums[middle] itself, and the global minimum is at middle or to its left. Move right to middle, not to middle - 1, because middle may be the answer.

    Each pass halves the window, and the loop ends when it has one index, which holds the minimum.

    On [4, 5, 6, 7, 0, 1, 2] the window shrinks like this:

    left=0 right=6 middle=3 nums[middle]=7 nums[right]=2
    left=4 right=6 middle=5 nums[middle]=1 nums[right]=2
    left=4 right=5 middle=4 nums[middle]=0 nums[right]=1
    left=4 right=4 -> 0
    

    Step by step

    1. Declare left and right as mutable variables: 0 and nums.len() - 1. The minimum can be anywhere, so the window starts as the whole vector. The vector is never empty, so the subtraction is safe.
    2. Loop while left < right. It stops when the window is a single index, which is where the minimum is.
    3. Compute middle as left + (right - left) / 2, which rounds down and can't overflow.
    4. If nums[middle] > nums[right], the minimum is to the right of middle: set left to middle + 1.
    5. Otherwise the minimum is at middle or to its left: set right to middle.
    6. After the loop, left and right meet at the minimum, so the function ends with nums[left].

    The solution in Rust

    impl Solution {
        fn find_min(nums: Vec<i32>) -> i32 {
            let mut left = 0;
            let mut right = nums.len() - 1;
            while left < right {
                let middle = left + (right - left) / 2;
                if nums[middle] > nums[right] {
                    left = middle + 1;
                } else {
                    right = middle;
                }
            }
            nums[left]
        }
    }
    

    The Rust details worth a closer look:

    • usize everywhere. nums.len() - 1 is a usize, so left and right are too, and they index nums directly. Neither is ever decreased below its starting value, so there is no underflow: left only grows and right only moves to middle, which is at least left.
    • The shortcut for the midpoint. left + (right - left) / 2 rounds down, so middle is always less than right inside the loop. That is why right = middle shrinks the window, and why left = middle + 1 never passes right.
    • The value comes out of the vector by copy. The function returns nums[left], an i32, which is Copy, so indexing the vector it owns is enough. There is no need for clone().
    • Last expression. nums[left] has no semicolon, so it is the function's value.

    Complexity

    Time: O(log n). Each pass at least halves the window.

    Space: O(1). Only left, right and middle are stored.

    Edge cases and common mistakes

    • A vector that wasn't rotated. [11, 13, 15, 17] gives 11. Every middle is smaller than the last element, so right keeps moving left until it reaches index 0.
    • A single element. [9] gives 9: the loop doesn't run.
    • Two elements. [2, 1] gives 1 and [1, 2] gives 1. For [2, 1], middle is 0, nums[0] is bigger than nums[1], and left moves to 1.
    • Comparing with nums[left] instead of nums[right]. In an unrotated vector, nums[middle] is bigger than nums[left], yet the minimum is on the left. A version that moves left past middle whenever nums[middle] > nums[left] returns 15 for [11, 13, 15, 17], 2 for [4, 5, 6, 7, 0, 1, 2] and 3 for [5, 6, 7, 8, 9, 1, 2, 3, 4], all wrong.
    • Setting right = middle - 1. When nums[middle] is the minimum, this discards it. The assignment must keep middle in the window.
    • Using left <= right. With right = middle as the update, the window may stop shrinking when left equals right, and the loop would never end. The strict < is what guarantees it stops.
    • Returning an index. The function returns the value nums[left], not the index left.

    Testing

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