Start learning free

LESSON 331 OF 500 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in C++

Practice O(log n)

You are given a vector of distinct integers nums that was sorted in ascending order and then possibly rotated at an unknown index k (0 <= k < nums.size()): its first k elements were moved, in the same order, to its end. For example, [0,1,2,4,5,6,7] rotated at k = 3 becomes [4,5,6,7,0,1,2], and with k = 0 it stays as it was.

Given nums after the rotation, return its minimum element.

 

Example 1:

Input: nums = [3,4,5,1,2]
Output: 1
Explanation: The original vector was [1,2,3,4,5], rotated at k = 2.

Example 2:

Input: nums = [4,5,6,7,0,1,2]
Output: 0
Explanation: The original vector was [0,1,2,4,5,6,7], rotated at k = 3. The middle element, 7, is bigger than the last one, 2, so the values drop somewhere after the middle: that drop is where the minimum is.

Example 3:

Input: nums = [11,13,15,17]
Output: 11
Explanation: The vector was not rotated (k = 0), so the minimum is its first element.

 

Constraints:

  • 1 <= nums.size() <= 106
  • -109 <= nums[i] <= 109
  • All the values of nums are distinct.
  • nums is sorted in ascending order and possibly rotated.

Note:

Your algorithm should run in O(log n) time and use O(1) extra space.

STEP 1 OF 6
    Ctrl + Enter to check

    Find Minimum In Rotated Sorted Array in C++

    Keep going with C++500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free