v9.1.1
Menu

Find Minimum in Rotated Sorted Array

mediumFREEBinary SearchBlind 75

Given a sorted rotated array of unique elements nums, return the minimum element.

The array was originally sorted in ascending order, then rotated between 1 and n times. You must solve it in O(log n) time.

Example

Input
3,4,5,1,2
Output
1
Reasoning
  • The input 3,4,5,1,2 is the sorted array [1,2,3,4,5][1, 2, 3, 4, 5] rotated 33 times: each rotation moves the last element to the front, so the final three values 3,4,53, 4, 5 now lead.
  • Rotation splits the array into two ascending runs, [3,4,5][3, 4, 5] and [1,2][1, 2]. Every value in the first run is larger than every value in the second, because the first run holds the top of the original order.
  • The minimum is therefore the first value of the second run. It is the only position where a value is smaller than its left neighbour: 5>15 > 1 is the single "drop", while 3<4<53 < 4 < 5 and 1<21 < 2 rise.
  • So the answer is 11, the original first element, which matches the output 1.
  • Notice that rotating nn times returns the array to its sorted order, as in [11,13,15,17][11, 13, 15, 17]: there is no drop at all and the minimum is simply the first value, 1111.

Constraints

  • 1 <= len(nums) <= 5000
  • -5000 <= nums[i] <= 5000
  • All values are unique
  • nums was sorted then rotated

Learn this in

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.