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
- 1 ≤ nums.length ≤ 5000
- -5000 ≤ nums[i] ≤ 5000
- All values are distinct
numsis a sorted array rotated 1 to n times
Edge cases to test
- Not rotated at all
- Two elements
- The minimum is the last element
Follow-up questions
- What if there are duplicates?
- When
nums[mid] == nums[hi]you can’t tell which side holds the minimum, so drophiby 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
- Binary Search (Easy)
- Search Insert Position (Easy)
- Sqrt(x) (Easy)
- Find First and Last Position of Element in Sorted Array (Medium)
- Search in Rotated Sorted Array (Medium)
- Find Peak Element (Medium)
- Single Element in a Sorted Array (Medium)
- Koko Eating Bananas (Medium)
- Kth Smallest Element in a Sorted Matrix (Medium)
- Allocate Minimum Pages (Hard)
- Median of Two Sorted Arrays (Hard)
- Time Based Key-Value Store (Medium)