Find Minimum in Rotated Sorted Array

Medium Binary SearchArray

Problem

An ascending sorted array of unique values was rotated at some pivot. Return the minimum element. Aim for O(log n).

Example 1 Input: nums = [3,4,5,1,2] Output: 1
Example 2 Input: nums = [4,5,6,7,0,1,2] Output: 0
Example 3 Input: nums = [11,13,15,17] Output: 11

Constraints

Approach — Binary Search

This is a Binary Search problem. The idea: repeatedly halve the search space, discarding the half that can't contain the answer. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: O(log n) time.

Solution code

Python

class Solution:
    def findMin(self, nums):
        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]

Java

class Solution {
    public int findMin(int[] nums) {
        int l = 0, r = nums.length - 1;
        while (l < r) {
            int m = l + (r - l) / 2;
            if (nums[m] > nums[r]) l = m + 1;
            else                   r = m;
        }
        return nums[l];
    }
}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Find Minimum in Rotated Sorted Array interactively → ← All solutions