Find Minimum in Rotated Sorted Array

Binary search — compare mid to right end to decide which half holds the rotation pivot.

Medium
Time O(log n) Space O(1)
LeetCode
3 min read
binary-search array

Problem#

A sorted array has been rotated at some pivot. All values are unique. Return the minimum.

Examples#

  • [3,4,5,1,2]1.
  • [4,5,6,7,0,1,2]0; [11,13,15,17]11.

Constraints#

  • 1 <= n <= 5000.

Approach#

Binary search. If nums[mid] > nums[hi], the min is in the right half; shrink lo = mid + 1. Otherwise the min is at mid or in the left half; hi = mid.

Solution#

Find Minimum in Rotated Sorted Array
class Solution {
public:
int findMin(vector<int>& nums) {
int lo = 0, hi = nums.size() - 1;
while (lo < hi) {
int m = (lo + hi) / 2;
if (nums[m] > nums[hi]) lo = m + 1;
else hi = m;
}
return nums[lo];
}
};

Editorial#

Comparing to the right end is robust to rotation: nums[mid] > nums[hi] means the sorted part is on the right of mid, so the pivot (and minimum) is mid+1..hi. Otherwise the array from mid..hi is already sorted and mid is a candidate min.

Complexity#

  • Time: O(log n).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.