Start learning free

LESSON 100 OF 314 · BINARY SEARCH

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

    TYPESCRIPT · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in TypeScript, explained

    Problem overview

    The method findMin receives nums, an array of distinct integers that was sorted in ascending order and then possibly rotated: a rotation at index k moves the first k elements, in the same order, to the end. It returns the smallest element. The algorithm must run in O(log n) time with O(1) extra space.

    For [4, 5, 6, 7, 0, 1, 2], the original sorted array was [0, 1, 2, 4, 5, 6, 7] rotated at k = 3, and the minimum is 0. For [11, 13, 15, 17] there was no rotation, so the minimum is the first element, 11.

    Approach: compare the middle with the last element

    Scanning the array, or calling Math.min(...nums), is O(n). A rotated array has a single drop, where a big value is followed by a small one, and the minimum is right after it. Binary search can find that drop without looking at every element.

    Look at nums[middle] and nums[right]:

    • If nums[middle] > nums[right], the values must drop somewhere between them, so the minimum lies to the right of middle. And nums[middle] itself is bigger than another element, so it can't be the minimum.
    • Otherwise nums[middle] is smaller than nums[right] (the values are distinct), and everything from middle to right is sorted. The minimum is at middle or to its left.

    Each pass keeps the minimum inside the window and cuts the window roughly in half. When the window is a single index, that index holds the minimum.

    On [4, 5, 6, 7, 0, 1, 2] the window starts as indices 0 to 6. The middle, index 3, holds 7, which is bigger than the last value 2, so left moves to 4. The window 4 to 6 has its middle at index 5, holding 1, which is not bigger than 2, so right moves to 5. The window 4 to 5 has its middle at index 4, holding 0, so right moves to 4. The window is one index, and nums[4] is 0.

    Step by step

    1. Set the window with one let: left is 0 and right is nums.length - 1. The minimum can be anywhere, so the window starts as the whole array.
    2. Loop while left < right. The loop stops when the window is down to one index, and that index holds the minimum. This is <, not <=.
    3. Compute middle as Math.floor(left + (right - left) / 2). Dividing numbers keeps the fraction, and an index must be whole.
    4. If nums[middle] > nums[right], move left to middle + 1. The minimum is to the right of middle.
    5. Otherwise move right to middle, not middle - 1, because nums[middle] may be the minimum itself.
    6. Return nums[left]. The two pointers meet at the minimum.

    The solution in TypeScript

    class Solution {
        findMin(nums: number[]): number {
            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 TypeScript details:

    • Math.floor is needed. A number is a double, so (0 + 7) / 2 is 3.5, and nums[3.5] is undefined. Math.floor makes the index whole. Here left never exceeds right, so the result is always a valid index.
    • Why left + (right - left) / 2. It picks the lower of two middles when the window has an even length. That matters for the right = middle branch: with a two-element window, middle equals left, so the window always shrinks and the loop ends.
    • Return value. The function returns a value, not an index, so it ends with nums[left]. The array is not changed.

    Complexity

    Time: O(log n). Each pass discards at least half of the window, so there are about log2 n passes with constant work each.

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

    Edge cases and common mistakes

    • Comparing with nums[left] instead of nums[right]. In an array that wasn't rotated, nums[middle] is bigger than nums[left], yet the minimum is on the left. A version that moves left in that case returns 15 for [11, 13, 15, 17] instead of 11.
    • Using right = middle - 1. It can step over the minimum when nums[middle] is the minimum itself. For [2, 0, 1] that version returns 2 instead of 0.
    • Using left <= right. With right = middle in the loop, the window may never shrink when left equals right, so the loop would not end.
    • One element. [1] never enters the loop and returns 1.
    • No rotation. The middle is never bigger than the last value, so right keeps moving left to 0, and the first element is returned.
    • Duplicates. With repeated values, nums[middle] == nums[right] would not say which side holds the minimum. The lesson's constraints say all values are distinct.

    Testing

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