Start learning free

LESSON 100 OF 314 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in Swift: 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.count.

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

    SWIFT · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Swift, explained

    Problem overview

    The method findMin receives an array of distinct integers, nums, that was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same order, to the end. It returns the smallest element. The statement asks for O(log n) time and O(1) extra space.

    For [3, 4, 5, 1, 2] the answer is 1: the original array was [1, 2, 3, 4, 5], rotated by 2. 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). To get O(log n), use the shape of the array: its values rise, drop once at the rotation point, and rise again. The minimum is the first value after the drop, or the first element when there was no rotation.

    Comparing nums[middle] with nums[right] tells which side of the window holds the drop:

    • If nums[middle] > nums[right], the values go down somewhere after middle. The minimum is to the right, and middle itself can't be it, because it is bigger than another element.
    • Otherwise nums[middle] is smaller than nums[right] and everything from middle to right is rising. The minimum is at middle or to its left.

    Each pass drops about half of the window, and the loop stops when one index is left. Here is the search on [4, 5, 6, 7, 0, 1, 2]:

    left=0 right=6 middle=3 nums[middle]=7 nums[right]=2
    left=4 right=6 middle=5 nums[middle]=1 nums[right]=2
    left=4 right=5 middle=4 nums[middle]=0 nums[right]=1
    end left=4 right=4
    

    In the first pass 7 is bigger than 2, so the minimum is to the right of index 3 and left becomes 4. In the second pass 1 is smaller than 2, so right moves to 5. In the third, 0 is smaller than 1, so right moves to 4, and the window is one index: nums[4], which is 0.

    Step by step

    1. Set up the window. left and right start at 0 and nums.count - 1. The minimum can be anywhere, so the window is the whole array. Both are var because the loop moves them.
    2. Loop while left < right. This time it is <, not <=: the loop stops when the window is a single index, and that index holds the minimum.
    3. Compute middle as left + (right - left) / 2, a let. Integer division rounds down, and the form never overflows.
    4. If nums[middle] > nums[right], set left = middle + 1. The drop lies between middle and right, so the minimum is past middle.
    5. Otherwise, set right = middle. Not middle - 1: nums[middle] may be the minimum.
    6. Return nums[left] once the pointers meet.

    The solution in Swift

    class Solution {
        func findMin(_ nums: [Int]) -> Int {
            var left = 0, right = nums.count - 1
            while left < right {
                let middle = left + (right - left) / 2
                if nums[middle] > nums[right] {
                    left = middle + 1
                } else {
                    right = middle
                }
            }
            return nums[left]
        }
    }
    

    Swift details worth knowing:

    • Two variables on one line. var left = 0, right = nums.count - 1 declares two separate Int variables.
    • The result is not optional. The method returns nums[left] as a plain Int. An empty array would make nums[left] an index error, and the constraints promise at least one element.
    • Integer division. (right - left) / 2 truncates, and since right - left is positive inside the loop, middle is always strictly below right. That is why left = middle + 1 and right = middle both shrink the window, and the loop always ends.
    • No unsafe arithmetic. Swift traps on overflow, and left + (right - left) / 2 keeps every intermediate value inside the array's index range.

    Complexity

    Time: O(log n). Each pass discards at least half of the window, so the loop runs about log base 2 of n times.

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

    Edge cases and common mistakes

    • No rotation. [11, 13, 15, 17] returns 11. In every pass nums[middle] is smaller than nums[right], so right keeps moving left until it reaches index 0.
    • One element. [1] returns 1 without entering the loop.
    • Two elements. [2, 1] returns 1 and [1, 2] returns 1.
    • Rotated by one or by almost the whole length. [5, 1, 2, 3, 4] and [2, 3, 4, 5, 1] both return 1.
    • Comparing with nums[left] instead of nums[right]. On a non-rotated array, nums[middle] is bigger than nums[left] although the minimum is on the left. With that comparison, [11, 13, 15, 17] returns 15 instead of 11.
    • Using right = middle - 1. It can discard the minimum itself, when middle holds it.
    • Using left <= right. With right = middle, a window of one index would never shrink, and the loop would run forever.

    Testing

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