Find Minimum in Rotated Sorted Array

Find the smallest value of a rotated sorted array by comparing the middle with the right end and keeping the half that holds the drop.

Time O(log n)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

The minimum sits right after the drop. Compare nums[mid] with nums[hi]: if nums[mid] is bigger, the values fall somewhere between mid and hi, so the drop and the minimum are to the right of mid. Otherwise mid..hi rises steadily, so the minimum is mid itself or to its left. The window shrinks until lo == hi, and that index holds the minimum.

Code

public static int FindMin(int[] nums) {
    int lo = 0, hi = nums.Length - 1;
    while (lo < hi) {
        int mid = lo + (hi - lo) / 2;
        if (nums[mid] > nums[hi]) lo = mid + 1;
        else hi = mid;
    }
    return nums[lo];
}

Tips

In the .NET library

nums.Min() from LINQ gives the same answer in O(n); the point here is O(log n) by using the sorted structure.