Start learning free

LESSON 100 OF 314 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in JavaScript: 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.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

    JAVASCRIPT · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in JavaScript, explained

    Problem overview

    The method findMin(nums) receives an array of distinct integers that 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. The statement asks for O(log n) time and O(1) extra 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 whole array, or calling Math.min on it, finds the minimum in O(n). To reach O(log n) the search must discard half of the array on every step, as in binary search, using the shape of a rotated array: a rising run, a single drop, and another rising run. The minimum is the element right after the drop, or the first element when there is no drop.

    Compare nums[middle] with nums[right]:

    • If nums[middle] > nums[right], the values must drop somewhere between them, because in a sorted stretch the middle would be smaller than the last element. The minimum lies to the right of middle, and middle itself can't be it, so move left to middle + 1.
    • Otherwise nums[middle] < nums[right] (the values are distinct), so the stretch from middle to right is sorted. The minimum is at middle or to its left. Move right to middle, keeping middle in the window, since it may be the answer.

    Every pass keeps the minimum inside the window [left, right] and shrinks it, so the loop ends when one index is left, and that index holds the minimum.

    The right-hand side is the right thing to compare with. Comparing with nums[left] fails on arrays that were not rotated, where the middle is bigger than nums[left] and yet the minimum is on the left.

    On [4, 5, 6, 7, 0, 1, 2] the search goes like this:

    leftrightmiddlenums[middle]nums[right]action
    063727 > 2: left = 4
    465121 < 2: right = 5
    454010 < 1: right = 4

    Now left and right are both 4, and nums[4] is 0. For [11, 13, 15, 17] the middle is never bigger than the last element, so right keeps moving left until it reaches index 0, and the answer is 11.

    Step by step

    1. Declare left and right with one let: 0 and nums.length - 1. The minimum can be anywhere, so the window starts as the whole array.
    2. Loop while left < right. This time it is <, not <=: the loop stops when one index is left, and that index holds the minimum.
    3. Compute middle as Math.floor(left + (right - left) / 2). The division may give a fraction, and an index has to be whole.
    4. If nums[middle] > nums[right], move left to middle + 1. The middle value is bigger than another element, so it can't be the minimum.
    5. Otherwise move right to middle, not middle - 1, because nums[middle] might be the minimum.
    6. Return nums[left] after the loop, when left and right meet.

    The solution in JavaScript

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

    Some JavaScript details worth knowing:

    • Division keeps the fraction. 7 / 2 is 3.5, not 3, so the midpoint needs Math.floor before it is used as an index. Math.floor rounds down, which is what keeps middle from reaching right while left < right. That matters: right = middle only makes progress if middle is below right.
    • One let for two variables. let left = 0, right = nums.length - 1; declares both, and both are reassigned in the loop.
    • The result is a value, not an index. The function returns nums[left]. Returning left would give the position of the minimum, which is the rotation point.
    • Reading out of range gives undefined. For an empty array, nums[0] is undefined, and this function returns that. The constraints promise at least one element.

    Complexity

    Time: O(log n). Each pass at least halves the window: it either moves left past middle or pulls right in to middle, and both discard about half of the elements. For a million elements that is about 20 passes.

    Space: O(1). Only three indices are stored.

    Edge cases and common mistakes

    • A single element. [1] never enters the loop, and the function returns 1.
    • Two elements. [2, 1] and [1, 2] both return 1. For [2, 1] the middle is index 0 and 2 is bigger than 1, so left moves to 1.
    • No rotation. [1, 2, 3, 4] returns 1 and [11, 13, 15, 17] returns 11. The minimum is the first element, and right moves toward it.
    • Rotation by one in each direction. [5, 1, 2, 3, 4] and [2, 3, 4, 5, 1] both return 1.
    • Negative numbers. [-3, -2, -9, -7, -5] returns -9. Only comparisons are used, so signs don't matter.
    • Comparing with nums[left]. Replacing nums[right] with nums[left] in the test gives 15 for [11, 13, 15, 17] and 2 for [4, 5, 6, 7, 0, 1, 2], both wrong.
    • Using right = middle - 1. This can discard the minimum itself. For [3, 1, 2] that version returns 3 instead of 1.
    • Using left <= right. With right = middle the window may stop shrinking when left equals right, so the loop would never end. The condition must be left < right.
    • Duplicates. The statement guarantees distinct values. With duplicates, nums[middle] can equal nums[right] and the comparison no longer says which side holds the drop.

    Testing

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