InterviewPrepKit

Home / Coding / Binary Search

Find Minimum in Rotated Sorted Array

medium Original β†—
Solving tips
  • Binary search on structure, not a value: the array is two sorted runs, and you search for the rotation point (the minimum).
  • Compare nums[mid] to nums[hi]: if nums[mid] > nums[hi] the minimum is strictly right (lo = mid+1), else it is at mid or left (hi = mid).
  • Use the lo < hi / hi = mid convention (not hi = mid-1) since mid itself may be the minimum; anchor to nums[hi], not nums[lo], which is ambiguous.
  • O(log n) time, O(1) space; the fully-sorted (rotated n times) case falls out correctly, returning nums[0].

Problem

An array of distinct integers was sorted in ascending order, then rotated some number of times between 1 and n: rotating once moves the last element to the front. For example, [0, 1, 2, 4, 5, 6, 7] rotated 4 times becomes [4, 5, 6, 7, 0, 1, 2] (rotating n times gives back the original).

Given the rotated array nums, return its minimum element in O(log n) time.

Examples

  • Input: nums = [3, 4, 5, 1, 2] β†’ Output: 1 (Original [1, 2, 3, 4, 5] rotated 3 times; the minimum is 1.)
  • Input: nums = [4, 5, 6, 7, 0, 1, 2] β†’ Output: 0 (The β€œdrop” from 7 to 0 marks where the minimum sits.)
  • Input: nums = [11, 13, 15, 17] β†’ Output: 11 (Rotated n times β€” the array is fully sorted, so the first element is the minimum.)

Constraints

  • 1 <= nums.length <= 5000
  • -5000 <= nums[i] <= 5000
  • All elements are unique.
  • The array was sorted, then rotated between 1 and n times.
  • Required time complexity: O(log n).

Think about it first

Hint 1 Picture the rotated array as two sorted runs: a higher run followed by a lower run (or just one run if the rotation brought it back to sorted). Where does the minimum live?
Hint 2 Compare `nums[mid]` with `nums[hi]` (the last element). If `nums[mid] > nums[hi]`, which run is `mid` in β€” and on which side of `mid` must the minimum be?
Hint 3 Binary search with `lo, hi = 0, n - 1`: while `lo < hi`, if `nums[mid] > nums[hi]` the minimum is strictly right of mid (`lo = mid + 1`); otherwise `mid` itself might be the minimum (`hi = mid`). When the pointers meet, they sit on the answer.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.