Algo-Sim › Binary Search

Find Minimum in Rotated Sorted Array

Medium · Binary Search · step through it in Java, Python and C++ on your own input

Find the smallest value of a rotated sorted array by comparing the middle with the right end.

Problem

An array of distinct integers sorted in increasing order was rotated between 1 and n times, so [0, 1, 2, 4, 5, 6, 7] might become [4, 5, 6, 7, 0, 1, 2]. Given the rotated array nums, return its minimum element in O(log n) time.

Constraints

Edge cases to test

Follow-up questions

What if there are duplicates?
When nums[mid] == nums[hi] you can’t tell which side holds the minimum, so drop hi by one: O(log n) on average, O(n) worst case (LC 154).
Why compare with the right end, not the left?
The right end tells you which side of the rotation mid is on even when the array is not rotated; comparing with the left breaks on a sorted array.

Solution

Java

public 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 find_min(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = lo + (hi - lo) // 2
        if nums[mid] > nums[hi]: lo = mid + 1
        else: hi = mid
    return nums[lo]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    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];
    }
};

More Binary Search problems