Start learning free

LESSON 100 OF 314 · BINARY SEARCH

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

Practice O(log n) Read the full explanation

You get a list 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 < len(nums).

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

    PYTHON · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Python, explained

    Problem overview

    The method findMin receives a list 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. 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 of the rotated list.

    In [3, 4, 5, 1, 2] the minimum is 1, and in [11, 13, 15, 17], which was not rotated, it is 11, the first element. The lesson asks for O(log n) time and O(1) extra space. Calling min(nums) or scanning the list is O(n), so the sorted structure has to be used.

    Approach: compare the middle with the last element

    The rotated list rises, drops once at the rotation point, and rises again. The minimum is the element right after the drop, or the first element when there is no rotation. Binary search can locate it if each comparison tells which side of the middle the drop is on.

    The comparison that works is nums[middle] against nums[right]:

    • If nums[middle] > nums[right], the values must drop somewhere between them, because in a stretch with no drop every value is smaller than the last one. The minimum is to the right of middle, and middle itself can't be the minimum, since it is bigger than another element.
    • Otherwise nums[middle] < nums[right] (the values are distinct, and middle is always left of right inside the loop), and everything from middle to right is sorted. The minimum is at middle or to its left.

    Every pass keeps the minimum inside the window and discards about half of it. When the window is down to a single index, that index holds the minimum.

    On [4, 5, 6, 7, 0, 1, 2], the window starts at indexes 0 to 6 with middle 3, which holds 7. That is bigger than the last element, 2, so left moves to 4. Then middle is 5, which holds 1; it is smaller than 2, so right moves to 5. With the window at indexes 4 and 5, middle is 4, which holds 0, so right moves to 4. The window is a single index, and nums[4] is 0.

    Step by step

    1. Set the window: left, right = 0, len(nums) - 1. The minimum can be anywhere, so the window starts as the whole list.
    2. Loop while left < right. This time the comparison is <, not <=: the loop stops when one index is left, and that index holds the minimum.
    3. Compute middle as left + (right - left) // 2, using floor division.
    4. If nums[middle] > nums[right], the drop is to the right of middle. Move left to middle + 1, skipping middle, which can't be the minimum.
    5. Otherwise move right to middle, not middle - 1, because nums[middle] may be the minimum itself.
    6. After the loop, left and right have met. Return nums[left].

    The solution in Python

    class Solution:
        def findMin(self, nums: List[int]) -> int:
            left, right = 0, len(nums) - 1
            while left < right:
                middle = left + (right - left) // 2
                if nums[middle] > nums[right]:
                    left = middle + 1
                else:
                    right = middle
            return nums[left]
    

    The Python details that matter here:

    • // is floor division. It gives an integer index, where / would give a float that can't index a list.
    • The middle rounds down. With two elements left, middle equals left, never right. That matters for the else branch: right = middle always shrinks the window, so the loop can't get stuck. If middle could equal right, right = middle would change nothing.
    • The loop condition left < right means a one-element list skips the loop and returns its only element.
    • Tuple assignment in left, right = 0, len(nums) - 1 sets two variables in one line.

    Complexity

    Time: O(log n). Each pass discards about half of the window, so the loop runs at most about log2 n times, with constant work per pass.

    Space: O(1). The method keeps left, right and middle, and never copies the list.

    Edge cases and common mistakes

    • A list that was not rotated. [11, 13, 15, 17] gives 11. Every nums[middle] is smaller than nums[right], so right keeps moving left until it reaches index 0.
    • One element. [7] gives 7 without entering the loop.
    • Two elements. [2, 1] gives 1 and [1, 2] gives 1.
    • The minimum is the last element. [2, 3, 1] gives 1: nums[1] is bigger than nums[2], so left jumps to the last index and the loop ends.
    • Comparing with nums[left]. On [11, 13, 15, 17], nums[middle] is bigger than nums[left] even though nothing is rotated, and a rule that sends the search right on that comparison returns 15 instead of 11. Compare with nums[right].
    • Using right = middle - 1. It can discard the minimum. On [4, 5, 1, 2, 3] that version returns 4 instead of 1.
    • Using left = middle. Because the middle rounds down, left = middle can leave the window unchanged and loop forever. Moving to middle + 1 is safe because nums[middle] is known to be too big.

    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, 3, 1] gives 1.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free