Find Minimum in Rotated Sorted Array

mediumBinary Search16 stepsJava · Python · C++

A sorted array was rotated, e.g. [3, 4, 5, 1, 2]. Compare the middle with the rightmost element: if nums[mid] > nums[hi], the drop (and the minimum) is to the right of mid; otherwise the minimum is at mid or to its left.

▶ Watch the animated trace

Traced input: nums = [4, 5, 6, 7, 0, 1, 2] → 0. Original problem: neetcode.io/problems/find-minimum-in-rotated-sorted-array

Complexity

BestO(log n)
AverageO(log n)
WorstO(log n)
SpaceO(1)

Values are distinct, so every comparison discards half.

Key idea

Common mistakes

Solution

Java
int findMin(int[] nums) {
    int lo = 0, hi = nums.length - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] > nums[hi]) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    return nums[lo];
}
Python
def findMin(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
        else:
            hi = mid
    return nums[lo]
C++
int findMin(vector<int>& nums) {
    int lo = 0, hi = (int)nums.size() - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] > nums[hi]) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }
    return nums[lo];
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Not rotated
hi keeps moving left to index 0.
nums = [11, 13, 15, 17]11
Rotated by one
nums[0] > nums[1], so lo moves to 1.
nums = [2, 1]1
Single element
Already lo == hi.
nums = [1]1
Minimum at the end
The drop is at the last position.
nums = [2, 3, 4, 5, 1]1
← Search Insert PositionSearch a 2D Matrix →