Binary Search Searching a sorted array

235. Find Minimum in Rotated Sorted Array

Medium 147 DSA Sheet

You are given an array nums of distinct integers. It was made by sorting some integers in increasing order and then rotating the sorted array some number of times. Return the smallest value in nums.

Rotating an array once moves its last element to the front. For example, rotating [2, 4, 6, 8, 10] twice gives [8, 10, 2, 4, 6]. The number of rotations can be zero, so nums may still be sorted.

Aim for O(log n) time.

Example 1

Input: nums = [15, 22, 37, 41, -8, -3, 0, 9]

Output: -8

Explanation: The sorted array [-8, -3, 0, 9, 15, 22, 37, 41] was rotated four times, so its last four values moved to the front. The smallest value, −8, now sits at position 4, right after the largest value, 41.

Example 2

Input: nums = [3, 5, 8, 13, 21]

Output: 3

Explanation: The array was rotated zero times. It is still sorted, so the smallest value is the first one.

Example 3

Input: nums = [-4, -1, 6, 12, -20]

Output: -20

Explanation: The sorted array [-20, -4, -1, 6, 12] was rotated four times. That moved every value except −20 to the front, so the smallest value is now the last element.

Check your understanding

Work out the answer for this input before you write any code.

nums = [40, 50, 10, 20, 30]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -231 ≤ nums[i] ≤ 231 − 1
  • All values in nums are distinct.
  • nums is an array sorted in increasing order and then rotated between 0 and nums.length − 1 times.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.