Skip to content

Find Minimum in Rotated Sorted Array

Find the smallest value of a rotated sorted array in O(log n) by comparing the middle with the right end.

MediumBinary Search
Solve on LeetCode

The problem

You get an array nums of distinct integers that was sorted in increasing order and then rotated: some elements from the end were moved to the front, keeping their order. Return the smallest element. Your solution must run in O(log n) time.

Input nums = [11, 13, 15, 2, 5, 8]

Output 2

Before the rotation the array was [2, 5, 8, 11, 13, 15]; then 11, 13 and 15 moved to the front.

Input nums = [4, 6, 9]

Output 4

This array wasn't rotated, so the first number is the smallest.

How to spot the pattern

  • The array is sorted except for one break point, and O(log n) is required.
  • Comparing the middle with one end tells you which side of the break the middle is on.

The idea

A rotated array is two sorted runs, and the minimum is the first element of the second run. If nums[mid] > nums[hi], the break lies to the right of mid, so the minimum is in mid + 1..hi. Otherwise mid is already in the second run, so the minimum is at mid or to its left. Shrink the range this way until one element is left.

Brute force: Scan the whole array for the smallest value, which takes O(n) time.

Step by step

  1. 1Set lo = 0 and hi = n - 1.
  2. 2While lo < hi, compute mid.
  3. 3If nums[mid] > nums[hi], the minimum is to the right of mid, so set lo = mid + 1.
  4. 4Otherwise the minimum is at mid or to its left, so set hi = mid.
  5. 5When lo == hi, return nums[lo].

See the pattern move

The binary search pattern on a small example. Step through it, or press play.

Code

class Solution:
    def findMin(self, nums: List[int]) -> int:
        lo, hi = 0, len(nums) - 1
        while lo < hi:
            mid = lo + (hi - lo) // 2
            if nums[mid] > nums[hi]:
                lo = mid + 1  # the break, and the minimum, are to the right
            else:
                hi = mid  # the minimum is at mid or to its left
        return nums[lo]

Complexity

Time

O(log n)

Space

O(1)

Each step halves the range, and only two indices are stored.

Watch out for

  • Comparing nums[mid] with nums[lo] instead of nums[hi]: in an array that isn't rotated, like [1, 2, 3], nums[mid] > nums[lo] would send you right, away from the minimum.
  • Setting hi = mid - 1 when nums[mid] <= nums[hi], which can skip the minimum when it sits exactly at mid.

Follow-up questions

What if the array can contain duplicates?

When nums[mid] == nums[hi] you can't tell which side holds the minimum, so just drop hi by one. That stays correct, but the worst case becomes O(n), for example when almost every value is the same.

How many times was the array rotated?

As many times as the index of the minimum, which is lo when the loop ends.

In Hinglish

Mid ko right end se compare karo: mid bada hai toh minimum right mein hai, warna mid par ya uske left mein.

Related problems