The Runtime Theory
mediumleetcode#binary-search

Find Minimum in Rotated Sorted Array

Find the minimum element of a rotated sorted array by comparing midpoints with the high bound, narrowing to the side with the break.

The Runtime Theory Team1 min read
Solve it

solving happens on the judge — come back and mark it done

Sample cases

in[3,4,5,1,2]

out1

in[4,5,6,7,0,1,2]

out0

in[11,13,15,17]

out11

The machine must return the minimum of a rotated sorted array with distinct values. The insight: the minimum is the pivot point where the order breaks. Compare the midpoint against the high element: if nums[mid] > nums[hi], the pivot is in the right half; otherwise the right half is continuous, so the pivot lies in the left half including mid.

python
def find_min(nums):
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] > nums[hi]:
            lo = mid + 1
        else:
            hi = mid
    return nums[lo]

Steps: (1) narrow the window to the side that contains the break, (2) when lo == hi, that slot holds the minimum.

Time is O(log n). Space is O(1).

Trickiest edge case: an unrotated array like [11,13,15,17]. The minimum is at index 0; the comparison nums[mid] > nums[hi] is never true, so hi creeps left toward 0 — the loop ends at lo == hi == 0. The inclusive hi = mid (not mid - 1) is what keeps the minimum inside the window; dropping it loses the answer when mid itself is the minimum.

More practice in this topic

One dispatch a week

The trace behind each problem, the tradeoff that explains it, and one technical dispatch per week — no noise.

One technical dispatch per week. No noise.