Menu
CoddyTech

Find Minimum in Rotated Sorted Array

MediumBinary searchpython iconjava iconcpp iconc iconjs icon+10

A list of distinct integers was sorted in increasing order and then rotated: some number of elements, possibly zero, were taken from the front and moved to the back in the same order. For example, [2, 5, 9, 11, 13, 15, 17] rotated by 3 becomes [11, 13, 15, 17, 2, 5, 9]. You get the rotated list nums. Return its smallest value in O(log n) time.

Function

findMin(nums: integer-array) → integer
numsinteger-array
the rotated sorted list of distinct integers
Returnsinteger
the smallest value in nums

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -104 ≤ nums[i] ≤ 104
  • All values in nums are distinct.
  • nums is an increasing list rotated by some k with 0 ≤ k < nums.length; k = 0 leaves it unrotated.

Examples

Input
nums = [11, 13, 15, 17, 2, 5, 9]
Output
2
Explanation
The values climb from 11 to 17 and then fall to 2, where the second run starts. The search sees 17 > 9 at index 3, so the minimum is to its right; then 5 ≤ 9 and 2 ≤ 5 pull hi back until the range is index 4 alone, which holds 2.

lock icon+17 hidden tests on Submit

challenge icon

Follow-up

Can you return the k-th smallest value of nums in O(log n) time, without sorting it?

Reset code
def findMin(nums):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

nums = [11, 13, 15, 17, 2, 5, 9]

Expected

2