sagelearnai

Find Minimum in Rotated Sorted Array

Difficulty: Medium · Pattern: Binary Search · LeetCode #153

A sorted array of distinct integers was rotated some number of times (e.g., [1,2,3,4,5] → [4,5,1,2,3]). Return its minimum element in O(log n).

Examples

text
nums = [4, 5, 6, 1, 2, 3]  →  1
nums = [7, 9, 11, 13]      →  7    (rotated n times, i.e. not at all)
nums = [2, 1]              →  1

Hints

  1. Compare nums[mid] with nums[hi]. Which side must contain the "drop"?
  2. If nums[mid] > nums[hi], the minimum is strictly right of mid.

Approach

If nums[mid] > nums[hi], the rotation point (the minimum) lies in (mid, hi], so set lo = mid + 1. Otherwise mid..hi is sorted, so the minimum is at mid or to its left: hi = mid. When lo == hi, it's the minimum. Comparing with the right end (not the left) avoids the unrotated edge case.

Complexity

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

Python solution
def findMin(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]
JavaScript solution
function findMin(nums) {
  let lo = 0, hi = nums.length - 1;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (nums[mid] > nums[hi]) lo = mid + 1; else hi = mid;
  }
  return nums[lo];
}