Skip to content
GKgkml.dev
← Problem set
#153MediumBinary search

Find Minimum in Rotated Sorted Array

The tell: Sorted array that has been rotated, and the requirement says O(log n).

How you get there

  1. 1The minimum is the single point where the ascending order breaks.
  2. 2If nums[mid] > nums[hi], the break is to the right, so search there.
  3. 3Otherwise mid could itself be the minimum, so keep it in the range.

Solution

Python
def find_min(nums: list[int]) -> int:
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] > nums[hi]:
            lo = mid + 1      # minimum is strictly right of mid
        else:
            hi = mid          # mid may be the minimum, so keep it
    return nums[lo]
Time
O(log n)
Space
O(1)

What goes wrong

Comparing nums[mid] to nums[lo] instead of nums[hi] breaks on arrays that were not rotated at all.