Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Book a call

Coding · Binary search

Minimum of a rotated sorted array

Medium · Target 15 minutes · Binary search· Type asked at

An array of distinct integers was sorted in increasing order, then rotated left some unknown number of times, so that [0, 1, 4, 5, 6] might arrive as [4, 5, 6, 0, 1]. Given the rotated array, return its smallest value in O(log n) time.

Examples

InputOutputWhy
nums = [3, 4, 5, 1, 2]1Rotated three positions.
nums = [11, 13, 15, 17]11Not rotated at all, which is a rotation of zero.
nums = [2, 1]1The smallest input where the rotation matters.

Constraints

  • 1 ≤ n ≤ 5000
  • −5000 ≤ nums[i] ≤ 5000
  • All values are distinct
  • The array is a rotation of a sorted array

Hints

Hint 1

You cannot compare the middle element against a target, because there is no target. What can you compare it against?

Hint 2

Compare nums[mid] against nums[hi]. One of those two comparisons tells you which half the rotation point is in.

Hint 3

If nums[mid] > nums[hi], everything from lo to mid is above the minimum, so the answer is strictly to the right of mid. Otherwise mid could itself be the answer, so keep it.

Where people lose marks

  • Writing hi = mid - 1 in the second branch. The minimum can be at mid, and you have just discarded it.
  • Writing lo = mid in the first branch. With two elements left, mid equals lo and the loop never terminates.
  • Looping on lo <= hi. The invariant here is that the answer is always inside [lo, hi], so the loop ends when the range is one element: the condition is lo < hi.
  • Assuming an unrotated array is a special case that needs its own branch. It does not; nums[mid] < nums[hi] handles it.
  • This breaks with duplicates. [2, 2, 2, 0, 2] cannot be resolved in O(log n), and the honest answer in an interview is to say so.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.