Start learning free

LESSON 99 OF 314 · BINARY SEARCH

Search in Rotated Sorted Array in Scala: O(log n) Binary Search

Practice O(log n) Read the full explanation

You get an integer target and an array nums of different integers.

Return the index of target in nums, or -1 if nums doesn't have it.

The numbers in nums 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, [2,5,8,10,13] with k = 2 becomes [8,10,13,2,5]. With k = 0, nothing moves.

 

Example 1:

Input: nums = [15,18,22,3,7,11], target = 7
Output: 4
Explanation: The sorted array was rotated with k = 3.
So 3, 7 and 11 moved to the end.
7 is at index 4.

Example 2:

Input: nums = [9,12,2,5], target = 6
Output: -1
Explanation: 6 is not in the array.

Example 3:

Input: nums = [8], target = 8
Output: 0

 

Constraints:

  • 1 to 1,000,000 numbers.
  • All numbers are different.
  • target and each number are 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 11
    Ctrl + Enter to check

    SCALA · BINARY SEARCH

    Search 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. For example, [0,1,2,4,5,6,7] rotated at k = 3 becomes [4,5,6,7,0,1,2]. The method search receives the rotated array and an integer target, and returns the index of target, or -1 when it isn't there. The rotation point is not given.

    In Array(4, 5, 6, 7, 0, 1, 2), the target 0 is at index 4, and the target 3 isn't present, so the answers are 4 and -1. In Array(6, 7, 1, 2, 3, 4, 5) the target 7 is at index 1.

    Approach: binary search that finds the sorted half

    A loop over every element finds the target in O(n). The lesson asks for O(log n), which means binary search, even though the array as a whole is not sorted.

    The key idea: wherever the rotation point is, at least one of the two halves around the middle index is sorted. The values drop only once, at the rotation point, so the drop is in at most one half, and the other half rises from end to end. In a sorted half, comparing the target with the half's two ends tells for certain whether the target can be inside. So each step does the following:

    1. Check the middle element.
    2. Work out which half is sorted.
    3. If the target lies within that sorted half, keep it; otherwise keep the other half.

    Each step discards half of the remaining window, giving about log2(n) steps. On Array(4, 5, 6, 7, 0, 1, 2) with the target 0, the window moves like this:

    left=0 right=6 middle=3 nums(middle)=7
    left=4 right=6 middle=5 nums(middle)=1
    left=4 right=4 middle=4 nums(middle)=0
    

    In the first step the left half, 4 5 6 7, is sorted and doesn't contain 0, so the search continues on the right. In the second step the window is 0, 1, 2 and its middle is 1; the left half, 0 and 1, is sorted and contains 0, so the search moves left. The third step finds 0 at index 4.

    Step by step

    1. Set the window. left is 0 and right is nums.length - 1, both inclusive, in vars because the loop moves them.
    2. Loop while left <= right. With <=, a window of one element, where left equals right, still gets checked.
    3. Find the middle: val middle = left + (right - left) / 2. Integer division already rounds down. Adding half the distance to left avoids the overflow that (left + right) / 2 can cause.
    4. Return middle if nums(middle) == target. This check comes first, so the later steps only decide which half to drop.
    5. Is the left half sorted? Test nums(left) <= nums(middle). It uses <= because when left equals middle, the left half is one element, and one element is sorted.
    6. If so, is the target in it? Check nums(left) <= target && target < nums(middle). When true, drop the right half with right = middle - 1. The comparison with nums(middle) is strict because the middle element was already checked.
    7. Otherwise drop the left half: left = middle + 1. The target can only be in the right part, which may not be sorted, but it is the only place left.
    8. If the left half isn't sorted, the right half is. The rotation point is in the left half, so everything from middle to right rises.
    9. Is the target in the sorted right half? Check nums(middle) < target && target <= nums(right). When true, drop the left half with left = middle + 1.
    10. Otherwise drop the right half: right = middle - 1.
    11. After the loop, return -1. The window is empty, so every index that could hold the target was ruled out.

    The solution in Scala

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

    Scala details worth knowing:

    • return exits the method. Scala normally uses the last expression of a block as its value, and return is rare. Here it is useful for leaving the loop early when the target is found. Inside a plain while, it simply ends the method.
    • Integer division. (right - left) / 2 on two Ints truncates, so middle is the lower of two middle indices for an even-sized window.
    • Int overflow wraps silently. With left = 1500000000 and right = 2100000000, (left + right) / 2 evaluates to -347483648, while left + (right - left) / 2 gives 1800000000. The lesson's arrays have far fewer elements than that, but the safe form costs nothing.
    • var versus val. left and right change, so they are var. middle is recomputed in every pass as a fresh val.
    • Indexing with parentheses. nums(middle) reads an element of the Array[Int].
    • && short-circuits. In nums(left) <= target && target < nums(middle) both parts must hold, and the second is skipped if the first is false.

    Complexity

    Time: O(log n). Every pass of the loop either returns or removes at least half of the window, including middle itself. After about log2(n) passes the window is empty.

    Space: O(1). The method keeps only left, right and middle.

    Edge cases and common mistakes

    • A single element. Array(1) with target 1 returns 0, and with target 0 returns -1. The window left = right = 0 is checked because the loop condition is <=.
    • Two elements. In Array(3, 1) the middle is index 0, so left equals middle. The test nums(left) <= nums(middle) is true, the left half is one sorted element, and the target 1 falls through to left = middle + 1. The result is 1.
    • An array that wasn't rotated. Array(1, 2, 3, 4, 5) with target 4 returns 3. The left half is always sorted, and it works as an ordinary binary search.
    • Target at an end of the window. For Array(4, 5, 6, 7, 0, 1, 2), the target 4 gives 0 and the target 2 gives 6.
    • Using < in the loop condition. With left < right, a window of one element is never checked, and Array(1) with target 1 returns -1 instead of 0.
    • Using < for the sorted-left test. With nums(left) < nums(middle), a window where left equals middle is treated as unsorted on the left. For Array(3, 1) and target 1, that sends the search the wrong way and the result is -1 instead of 1.
    • Duplicates. The method relies on distinct values. With repeats, nums(left) <= nums(middle) can't tell which half is sorted.

    Testing

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