☰ All problems

29. Find Minimum in Rotated Sorted Array

MediumArrayBinary Search

An array of distinct integers was sorted in ascending order and then rotated some number of times; one rotation moves the last element to the front. After, say, two rotations [2,5,9,12,15] becomes [12,15,2,5,9]. Rotating an array of length n exactly n times leaves it unchanged.

Given the rotated array nums, return its smallest element in O(log n) time.

Example 1
Input: nums = [9,12,15,2,5]
Output: 2

Explanation: The original array [2,5,9,12,15] was rotated three times.

Example 2
Input: nums = [30,10,20]
Output: 10
Example 3
Input: nums = [1,4,6,8]
Output: 1

Explanation: The array is back in its original order, so the minimum is the first element.

Constraints

  • 1 <= nums.length <= 5000
  • -5000 <= nums[i] <= 5000
  • All values in nums are distinct
  • nums is an ascending array rotated between 1 and n times
💡 Hint 1

The minimum is the only element smaller than the one before it, the point where the array "drops". A linear scan finds it, but you can do better.

💡 Hint 2

Compare nums[mid] with nums[hi]. If nums[mid] is larger, the drop must be somewhere to the right of mid.

💡 Hint 3

Otherwise mid itself might be the minimum, so keep it in the window: hi = mid rather than mid - 1.

/**
 * @param {number[]} nums
 * @return {number}
 */
function findMin(nums) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc