Start learning free

LESSON 100 OF 314 · BINARY SEARCH

Find Minimum in Rotated Sorted Array in Scala: O(log n)

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

    SCALA · BINARY SEARCH

    Find Minimum In Rotated Sorted Array in Scala, explained

    Problem overview

    The array nums holds distinct integers that were sorted in ascending order and then possibly rotated: its first k elements were moved, in order, to the end. The method findMin returns the smallest element of the rotated array. The rotation point is not given, and it may be 0, which means the array wasn't rotated at all.

    For Array(3, 4, 5, 1, 2) the answer is 1, and for Array(4, 5, 6, 7, 0, 1, 2) it is 0. For Array(11, 13, 15, 17) the array wasn't rotated, so the minimum is its first element, 11.

    Approach: binary search on the drop

    Scanning every element finds the minimum in O(n). The lesson asks for O(log n), so it uses binary search. The array isn't sorted, but it has a clear shape: it rises, drops once at the rotation point, and rises again. The minimum is the element right after the drop, or the first element if there is no drop.

    At each step, compare the middle element with the last element of the window:

    • If nums(middle) is bigger than nums(right), the values must drop somewhere after middle, so the minimum is to its right.
    • Otherwise, everything from middle to right is sorted, so the minimum is at middle or somewhere to its left.

    The window halves on every pass, so the search takes about log2(n) steps.

    Comparing with the right end is deliberate. Comparing with the left end looks natural but breaks on an array that wasn't rotated: there nums(middle) is always bigger than nums(left), yet the minimum is on the left.

    Step by step

    1. Set the window. left is 0 and right is nums.length - 1, both in vars because the loop moves them. The minimum can be anywhere, so the window starts as the whole array.
    2. Loop while left < right. This time the strict comparison is right: the loop stops when the window is a single index, 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 the way (left + right) / 2 can.
    4. Middle bigger than the last element: the drop is after middle, and middle itself can't be the minimum because a smaller element exists, so left = middle + 1.
    5. Otherwise: nums(middle) is smaller than nums(right). Everything from middle to right is sorted, so the minimum is at middle or earlier: right = middle. It's not middle - 1, because nums(middle) may be the minimum itself.
    6. Return nums(left) after the loop, when left and right have met.

    On Array(4, 5, 6, 7, 0, 1, 2), the window shrinks like this:

    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
    left=4 right=4 -> 0
    

    In the first row 7 is bigger than 2, so left jumps to 4. In the second row 1 is smaller than 2, so right moves to 5, and in the third 0 is smaller than 1, so right moves to 4. The window is then one index, and nums(4) is 0.

    The solution in Scala

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

    Scala details worth knowing:

    • Arrays are indexed with parentheses. nums(left) reads an element, and square brackets are for type parameters.
    • return is optional. The method could end with nums(left) alone, since the last expression of a block is its value. The explicit return gives the same result.
    • var for the moving ends. left and right are reassigned in the loop. middle is a val declared inside the loop, created fresh on every pass.
    • Integer division truncates. With left = 4 and right = 5, middle is 4, the lower index. That's why right = middle always makes progress, while left = middle + 1 does too.
    • Overflow. Int arithmetic wraps silently. With left = 1500000000 and right = 2100000000, (left + right) / 2 gives -347483648, and left + (right - left) / 2 gives 1800000000.

    Complexity

    Time: O(log n). Each pass moves left to middle + 1 or right to middle, and either way the window shrinks to at most half of its size, rounded up. After about log2(n) passes it has one index.

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

    Edge cases and common mistakes

    • A single element. Array(7) skips the loop, because left equals right, and returns 7.
    • Two elements. Array(2, 1) returns 1: the middle is index 0, 2 is bigger than 1, and left becomes 1. Array(1, 2) returns 1 as well, with right moving to 0.
    • No rotation. Array(11, 13, 15, 17) returns 11. At every step nums(middle) is smaller than nums(right), so right keeps moving left until it reaches 0.
    • The minimum at the end. Array(2, 3, 4, 5, 1) returns 1.
    • The minimum just after the first element. Array(5, 1, 2, 3, 4) returns 1.
    • Comparing with nums(left). A version that moves left to middle + 1 when nums(middle) > nums(left) returns 15 on Array(11, 13, 15, 17) instead of 11.
    • Setting right = middle - 1. It can skip the minimum. On Array(3, 1, 2) the middle is 1, which is smaller than 2, so that version moves right past it and returns 3 instead of 1.
    • Using left <= right. With right = middle in the else branch, the window can stop shrinking, and the loop would never end.

    Testing

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