← DSA
MEDIUM

Find Minimum in Rotated Sorted Array

PracticeNeetCode ↗LeetCode ↗

A sorted array of unique integers has been rotated at some unknown pivot. Find the minimum element, in O(log n) time.

Example

Input nums = [4,5,6,7,0,1,2]
Output 0

Key Pointers

Step-by-Step Analysis

  1. Set left = 0, right = len(nums) - 1.
  2. While left is below right: compute mid.
  3. If nums[mid] is greater than nums[right], the rotation point lies to the right of mid, so move left to mid + 1.
  4. Otherwise, mid itself could be the minimum, so pull right down to mid.
  5. When left meets right, return nums[left].

Complexity

Time: O(log n) — Space: O(1)

Code

def findMin(nums: list[int]) -> int:
    left, right = 0, len(nums) - 1

    while left < right:
        mid = left + (right - left) // 2
        if nums[mid] > nums[right]:
            left = mid + 1
        else:
            right = mid

    return nums[left]

Code Explanation

How the solution above works, piece by piece.

  1. The array is two sorted runs; the minimum is where the second run starts.
  2. Compare nums[mid] with nums[right]. If it's bigger, mid is in the left (higher) run, so the minimum is strictly to the right: left = mid + 1.
  3. Otherwise mid is in the right run, so the minimum is mid or before it: right = mid (keep mid).
  4. Comparing with right rather than left also works when the array isn't rotated at all.
  5. The loop ends when left == right, on the minimum. O(log n).

Visual Walkthrough

Running it on nums = [4, 5, 6, 7, 0, 1, 2]:

trace405162730415267 > nums[right]=2 → min is right of mid45670121 ≤ nums[right]=2 → min is at mid or left45670120 ≤ nums[right]=1 → min is at mid or left4567012left = right = 4 → minimum 0
Each probe compares the middle with the right end to decide which half contains the drop point. Two probes narrow it to index 4, value 0.
midright / answer

Video Explanation

NeetCode — Binary Search, LeetCode 153