Start learning free

LESSON 100 OF 314 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in C#: O(log n) Binary Search

Practice O(log n) Read the full explanation

You get an array nums of different integers.

Return the smallest number in nums.

The numbers were sorted from smallest to largest. Then the array may have been rotated. A rotation moves the first k numbers to the end, in the same order. Here 0 <= k < nums.Length.

For example, [1,4,6,9] with k = 1 becomes [4,6,9,1]. With k = 0, nothing moves.

 

Example 1:

Input: nums = [21,30,4,9,16]
Output: 4
Explanation: The sorted array was rotated with k = 3.
So 4, 9 and 16 moved to the end.
The smallest number is 4.

Example 2:

Input: nums = [-6,-2,5,12]
Output: -6
Explanation: This array was not rotated (k = 0).
The first number is the smallest.

Example 3:

Input: nums = [40,-5]
Output: -5

 

Constraints:

  • 1 to 1,000,000 numbers.
  • All numbers are different.
  • Each number is from -109 to 109.
  • The array is sorted, then maybe rotated (see above).

Note:

Your algorithm should run in O(log n) time and use O(1) extra space.

STEP 1 OF 6
    Ctrl + Enter to check

    C# · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in C#, explained

    Problem overview

    The method FindMin receives an int[] called nums of distinct values that were sorted in ascending order and then possibly rotated: the first k elements were moved, in the same order, to the end. It returns the smallest element. The method must run in O(log n) time and use O(1) extra space.

    For {3, 4, 5, 1, 2} the answer is 1: the original array was {1, 2, 3, 4, 5} rotated at k = 2. For {4, 5, 6, 7, 0, 1, 2} the answer is 0. For {11, 13, 15, 17}, which was not rotated, the answer is its first element, 11.

    Approach: compare the middle with the last element

    Scanning every element finds the minimum in O(n). Because the array is two sorted runs, a binary search can do better. The minimum is exactly the rotation point: the one place where a value is smaller than the one before it (or index 0 if there was no rotation).

    Look at nums[middle] and nums[right], the last element of the current window:

    • If nums[middle] > nums[right], the values must drop somewhere after middle, so the minimum lies to its right. The middle itself is bigger than another element, so it can't be the minimum: move left to middle + 1.
    • Otherwise nums[middle] < nums[right] (the values are distinct, so they are never equal when middle < right). Everything from middle to right is sorted, so the minimum is at middle or to its left: move right to middle, not middle - 1, since middle may be the minimum.

    Why compare with right and not with left? In an array that was not rotated, nums[middle] is bigger than nums[left], yet the minimum is on the left. Comparing with nums[right] gives the right answer in both situations.

    Each pass halves the window, and the loop stops when one index remains. Trace {4, 5, 6, 7, 0, 1, 2}: with left = 0, right = 6 the middle is index 3, value 7, which is bigger than the last value 2, so left becomes 4. With left = 4, right = 6 the middle is index 5, value 1, not bigger than 2, so right becomes 5. With left = 4, right = 5 the middle is index 4, value 0, not bigger than 1, so right becomes 4. The window is the single index 4, and nums[4] is 0.

    Step by step

    1. Declare left = 0 and right = nums.Length - 1. The minimum could be anywhere, so the window starts as the whole array.
    2. Loop while left < right. Unlike in a search for a target, the loop stops when one index is left, because that index holds the minimum.
    3. Compute middle = left + (right - left) / 2. It rounds down and can't overflow.
    4. If nums[middle] > nums[right], set left = middle + 1: the minimum is to the right of middle.
    5. Otherwise set right = middle: the minimum is at middle or before it.
    6. Return nums[left]. Every pass kept the minimum inside the window, and the window is now one index.

    The solution in C#

    class Solution {
        public int FindMin(int[] nums) {
            int left = 0, right = nums.Length - 1;
            while (left < right) {
                int middle = left + (right - left) / 2;
                if (nums[middle] > nums[right]) {
                    left = middle + 1;
                } else {
                    right = middle;
                }
            }
            return nums[left];
        }
    }
    

    C# details worth knowing:

    • The loop can't run forever. Since left < right, middle is at least left and strictly less than right. Both updates therefore shrink the window: left = middle + 1 raises left, and right = middle lowers right.
    • Integer division truncates. With an even window length, middle is the lower of the two central indices, which is what the right = middle branch relies on.
    • Overflow wraps silently. int arithmetic is unchecked by default. The form left + (right - left) / 2 avoids the sum left + right exceeding int.MaxValue for very large arrays.
    • An empty array would throw. nums[0] on an empty array raises IndexOutOfRangeException. The lesson guarantees at least one element.

    Complexity

    Time: O(log n). Each pass at least halves the window (more precisely, it keeps at most the upper half or the lower half including the middle).

    Space: O(1). Only left, right and middle are kept.

    Edge cases and common mistakes

    • Not rotated. {11, 13, 15, 17} returns 11. The middle is never bigger than the last element, so right keeps moving left until it reaches index 0.
    • One element. {2} returns 2 without entering the loop.
    • Two elements. {2, 1} returns 1: the middle is index 0, value 2, which is bigger than 1, so left moves to index 1.
    • Rotation by one. {3, 4, 5, 1, 2} returns 1.
    • Setting right = middle - 1. It can skip the minimum when the middle itself is the minimum.
    • Comparing with nums[left]. It gives the wrong direction for an array that was not rotated.
    • Looping with left <= right. With right = middle this can loop forever when the window is one index.

    Testing

    • {3, 4, 5, 1, 2} gives 1.
    • {4, 5, 6, 7, 0, 1, 2} gives 0.
    • {11, 13, 15, 17} gives 11.
    • {2} gives 2.
    • {2, 1} gives 1.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free