Start learning free

LESSON 100 OF 314 · BINARY SEARCH

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

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

    KOTLIN · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Kotlin, explained

    Problem overview

    The function findMin receives an IntArray named nums of distinct integers that were sorted in ascending order and then possibly rotated: the first k elements were moved, in the same order, to the end. For example, [0, 1, 2, 4, 5, 6, 7] rotated with k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. With k = 0 the array stays as it was. The function returns the smallest element, in O(log n) time and O(1) extra space.

    For [3, 4, 5, 1, 2] the answer is 1, for [4, 5, 6, 7, 0, 1, 2] it is 0, and for the unrotated [11, 13, 15, 17] it is 11, the first element.

    Approach

    Scanning the whole array finds the minimum in O(n), and that is a fine first answer, but it ignores the order the array still has. The array rises, drops once at the rotation point, and rises again. The minimum sits right after the drop, or at index 0 when there is no rotation.

    Binary search can find that point. Compare the middle element with the last element of the window:

    • If nums[middle] > nums[right], the values must drop somewhere after middle, because in a sorted stretch every value is smaller than the last one. The minimum is to the right of middle, and middle itself can't be it, since a bigger value exists after it.
    • Otherwise nums[middle] is smaller than nums[right], so everything from middle to right is sorted. The minimum is at middle or to its left.

    Each pass drops about half of the window while keeping the minimum inside it, so the search needs O(log n) passes.

    Step by step

    1. Set the window. var left = 0 and var right = nums.size - 1. The minimum can be anywhere, so the window starts as the whole array. They are vars because the loop moves them.
    2. Loop while (left < right). This is <, not <=: the loop stops when the window is one index wide, and that index holds the minimum.
    3. Find the middle: val middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance to left can't overflow, unlike halving the sum.
    4. Drop the left side. If nums[middle] > nums[right], set left = middle + 1.
    5. Keep the middle. Otherwise set right = middle, not middle - 1: nums[middle] may be the minimum itself.
    6. Return nums[left]. Every pass kept the minimum inside the window, and now the window is a single index.

    Here are the passes 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
    answer index 4
    

    In the first pass, 7 is larger than 2, so the minimum is to the right and left jumps to 4. In the second, 1 is smaller than 2, so right moves to middle. In the third, 0 is smaller than 1, right becomes 4, and the window is one index wide.

    On the unrotated [11, 13, 15, 17] the comparison never finds a drop, so right keeps moving left until the window sits at index 0:

    left=0 right=3 middle=1 nums[middle]=13 nums[right]=17
    left=0 right=1 middle=0 nums[middle]=11 nums[right]=13
    answer index 0
    

    The solution in Kotlin

    class Solution {
        fun findMin(nums: IntArray): Int {
            var left = 0
            var right = nums.size - 1
            while (left < right) {
                val middle = left + (right - left) / 2
                if (nums[middle] > nums[right]) {
                    left = middle + 1
                } else {
                    right = middle
                }
            }
            return nums[left]
        }
    }
    

    Kotlin details worth knowing:

    • Integer division. / on two Int values truncates toward zero. Here right - left is never negative, so it rounds down, and middle is always below right while left < right. That guarantees right = middle shrinks the window.
    • Overflow. Int is 32 bits and wraps silently, so (left + right) / 2 can go negative for indices near 2 billion. The form left + (right - left) / 2 is safe. The lesson's arrays are smaller, but the habit costs nothing.
    • var for moving bounds. left and right change in every pass, so they are var; middle is new in each pass, so it is a val declared inside the loop.
    • No empty case. The constraints guarantee at least one element. For an empty IntArray, nums.size - 1 is -1, the loop doesn't run, and nums[0] throws an ArrayIndexOutOfBoundsException.

    Complexity

    Time is O(log n): the window loses about half of its indices in each pass. Extra space is O(1): three integers.

    Edge cases and common mistakes

    • Comparing with nums[left] instead of nums[right]. In an array that wasn't rotated, nums[middle] is bigger than nums[left], yet the minimum is on the left. A version that compares with nums[left] and moves left past middle returns 15 for [11, 13, 15, 17], instead of 11.
    • Setting right = middle - 1. When nums[middle] is the minimum, this throws it away.
    • Using <= in the loop condition. With right = middle, a window of one index would never shrink, and the loop would not end.
    • A single element. [7] gives 7: the loop doesn't run, and nums[0] is returned.
    • Two elements. [2, 1] gives 1 and [1, 2] gives 1.
    • Rotation by one in either direction. [2, 3, 4, 5, 1] and [5, 1, 2, 3, 4] both give 1.
    • Distinct values. The solution relies on all values being different: with equal values, nums[middle] equal to nums[right] would not show where the drop is.

    Testing

    Results the solution returns:

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