Skip to content
Problem 153 · LeetCode 153(opens in a new tab)

Find Minimum in Rotated Sorted Array

MediumArrays

You are given nums, an array of distinct whole numbers. It was sorted from small to large, then turned: some number of values were taken off the end and put back at the front, in order. It may also have been turned all the way round, so it looks untouched.

Return the smallest value in nums. Your solution has to run in O(log n) time.

Example 1

Input:  nums = [15, 18, 22, 26, 3, 7, 11]
Output: 3
Why:    the values drop from 26 to 3
2 more examples and the constraints

Example 2

Input:  nums = [8, 1, 3, 5]
Output: 1
Why:    only 8 was moved to the front

Example 3

Input:  nums = [2, 4, 6, 9]
Output: 2
Why:    turned all the way round, so the first value is smallest

Constraints

  • 1 ≤ length of nums ≤ 5,000
  • Each number is between −5,000 and 5,000
  • All the numbers are different
  • nums is a sorted array turned between 1 and n times

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Scan every valueO(n)
  2. Binary search against the right endO(log n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 5,000 numbersVerdict
Scan every valueO(n)
Correct, misses the O(log n) rule
Binary search against the right endO(log n)
Best; about 13 looks

n = how many numbers are in the array.

Edge cases to test

  • Not turned (or turned n times). [2, 4, 6, 9]: the answer is the first value.
  • One number. [7]: the loop never runs and 7 comes back.
  • Two numbers. [2, 1] and [1, 2] both give 1.
  • Minimum at the end. [2, 3, 4, 5, 1]: the drop is the very last step.

Common mistakes

  • Comparing mid with the left end, which cannot tell an untouched array from a turned one.
  • Writing hi = mid - 1 when nums[mid] is smaller, which can skip the minimum itself.
  • Using while lo <= hi with hi = mid, which loops forever once lo equals hi.

How to talk through it

  1. 1Clarify. Are all values distinct? Can the array be untouched? Is O(log n) required?
  2. 2Give the scan. A linear pass finds the minimum in O(n); say that it ignores the sorted order.
  3. 3Name the shape. Two rising runs; the minimum starts the second. The right end tells you which run mid is in.
  4. 4Code the search. Explain why it is lo = mid + 1 on one side and hi = mid on the other.
  5. 5Test out loud. Run an untouched array, a single value and a two-value array before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?