Find Minimum in Rotated Sorted Array

MediumBinary search

nums was sorted in ascending order with no repeated values, then rotated: some values from the front, possibly none, were moved to the back, keeping their order. [2, 4, 5, 8, 11] could now be [5, 8, 11, 2, 4].

Return the smallest value in nums. Aim for O(log n) time.

Examples

Example 1
Input:  nums = [5, 8, 11, 2, 4]
Output: 2

[2, 4, 5, 8, 11] had 2 and 4 moved to the back. 2 is the smallest.

Example 2
Input:  nums = [-3, 0, 6]
Output: -3

Nothing was moved, so the array is still sorted and its first value is the smallest.

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -5000 ≤ nums[i] ≤ 5000
  • All values in nums are different.

Stuck?

Hint 1

Compare the middle value with the last one. If the middle is larger, the drop to the smallest value lies to its right.

Hint 2

Binary search, keeping the smallest value inside [low, high] at every step. Each comparison of the middle with the high end tells you which half can be dropped, and whether the middle itself might be the answer.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur