150NeetCode 150

31.Find Minimum in Rotated Sorted Array

MediumBlind 75Binary Search ยท 4/7

Problem

An array of unique integers sorted in ascending order has been rotated between 1 and n times. Rotating [a0, a1, ..., a(n-1)] once gives [a(n-1), a0, a1, ..., a(n-2)]. For example [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2] (rotated 4 times) or stay [0,1,2,4,5,6,7] (rotated 7 times).

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

Examples

Input:  nums = [3, 4, 5, 1, 2]
Output: 1
Explanation: The original array was [1, 2, 3, 4, 5], rotated 3 times.
Input:  nums = [4, 5, 6, 7, 0, 1, 2]
Output: 0
Explanation: The original array was [0, 1, 2, 4, 5, 6, 7], rotated 4 times.
Input:  nums = [11, 13, 15, 17]
Output: 11
Explanation: Rotated 4 times (a full cycle), so the array is sorted and the minimum is the first element.

Constraints

  • n == nums.length
  • 1 <= n <= 5000
  • -5000 <= nums[i] <= 5000
  • All integers in nums are unique.
  • nums is sorted and rotated between 1 and n times.

๐Ÿ’ก Key Insight

A rotated sorted array is two ascending runs: a left run of large values followed by a right run of small values, and the minimum is the first element of the right run. Comparing nums[mid] with nums[right] tells us which run mid is in: if nums[mid] > nums[right], mid is in the left (large) run and the minimum is strictly to its right; otherwise mid is in the right run and the minimum is at mid or to its left.

Brute Force

TimeO(n)SpaceO(1).

Intuition

Scan the whole array and keep the smallest value seen.

Algorithm

  1. min = nums[0].
  2. For each value, min = Math.min(min, value).
  3. Return min.

Visualization

nums = [3, 4, 5, 1, 2]
min: 3 โ†’ 3 โ†’ 3 โ†’ 1 โ†’ 1   โ†’ return 1

Code

java
class Solution {
    public int findMin(int[] nums) {
        int min = nums[0];
        for (int value : nums) {
            min = Math.min(min, value);
        }
        return min;
    }
}

Complexity

  • Time: O(n) โ€” every element is inspected.
  • Space: O(1).

Complexity Comparison

Approach Time Space
Brute Force O(n) O(1)
Binary Search with Sorted-Window Check O(log n) O(1)
Binary Search Against Right End O(log n) O(1)

Common Pitfalls

  • Comparing nums[mid] with nums[l] in the l < r template โ€” for an unrotated array like [1,2,3], nums[mid] > nums[l] would wrongly push you right. Comparing with nums[r] avoids this.
  • Writing r = mid - 1 when nums[mid] < nums[r] โ€” mid itself may be the minimum and would be skipped.
  • Forgetting the "rotated n times" case where the array is fully sorted; both binary searches must return nums[0] there.
  • This logic relies on unique values. With duplicates (LeetCode 154) you need an extra r-- step when nums[mid] == nums[r].