Start learning free

LESSON 99 OF 314 · BINARY SEARCH

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

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

    SWIFT · BINARY SEARCH

    Search In Rotated Sorted Array in Swift, explained

    Problem overview

    The method search 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. Given nums after the rotation and a target, it returns the index of target, or -1 if it isn't there. The statement asks for O(log n) time and O(1) extra space.

    For nums = [4, 5, 6, 7, 0, 1, 2] and target = 0, the answer is 4. For target = 3, the answer is -1.

    Approach: find a sorted half, then decide

    A loop that checks every element finds the target in O(n), which is too slow for the target complexity. Plain binary search needs a sorted array, and a rotated array isn't sorted: its values rise, drop once at the rotation point, and rise again.

    The lesson's key idea is that, wherever the rotation point is, at least one of the two halves around middle is sorted. The values drop only once, so the drop lies in at most one half, and the other half rises from end to end. A sorted half can be tested with its two ends: target is inside it exactly when it lies between them. If it is, search there. If not, it can only be in the other half. Every pass drops half of the window, which gives O(log n).

    Here is the search for 0 in [4, 5, 6, 7, 0, 1, 2]:

    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
    found 4
    

    In the first pass, nums[left] is 4 and nums[middle] is 7, so the left half [4, 5, 6, 7] is sorted. The target 0 isn't between 4 and 7, so the left half is dropped. The second pass has nums[left] = 0 and nums[middle] = 1: the left half is sorted, 0 is at least nums[left] and less than 1, so the search moves left and finds it at index 4.

    Step by step

    1. Set up the window. left and right start at 0 and nums.count - 1, both inclusive, so the window is everything from left to right.
    2. Loop while left <= right. Use <=: when they are equal, one element is still left to check.
    3. Compute middle as left + (right - left) / 2. Integer division already rounds down, and adding half the distance to left never overflows, unlike halving the sum.
    4. Check for the target. If nums[middle] equals target, return middle. After this check, the steps only decide which half to drop.
    5. Find the sorted half. If nums[left] <= nums[middle], the left half is sorted. The <= matters: when left equals middle, the left half is a single element, and one element is sorted.
    6. Target in the sorted left half? If nums[left] <= target and target < nums[middle], set right = middle - 1. The comparison with nums[middle] is strict, because that element was already checked.
    7. Otherwise it can't be in the left half, so set left = middle + 1.
    8. If the left half isn't sorted, the right half, from middle to right, is.
    9. Target in the sorted right half? If nums[middle] < target and target <= nums[right], set left = middle + 1.
    10. Otherwise set right = middle - 1.
    11. Return -1 after the loop: the window is empty, and every index that could hold the target has been ruled out.

    The solution in Swift

    class Solution {
        func search(_ nums: [Int], _ target: Int) -> Int {
            var left = 0, right = nums.count - 1
            while left <= right {
                let 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
        }
    }
    

    Swift details worth knowing:

    • Two variables in one line. var left = 0, right = nums.count - 1 declares two Int variables. They are var because the loop moves them.
    • middle is a let. It is computed fresh in every pass of the loop, so a constant is enough.
    • No optional result. The method returns a plain Int, with -1 meaning "not found", the way the lesson asks.
    • Integer division truncates toward zero. Here right - left is never negative inside the loop, so / 2 rounds down.
    • Overflow would stop the program. In Swift, arithmetic overflow traps. With a 64-bit Int and arrays of at most a million elements, neither form of the midpoint overflows, but left + (right - left) / 2 is the habit that stays safe.

    Complexity

    Time: O(log n). Each pass of the loop either returns or discards at least half of the window, so there are at most about log base 2 of n passes.

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

    Edge cases and common mistakes

    • One element. [1] with target 1 returns 0, and with target 0 returns -1.
    • Two elements. [3, 1] with target 1 returns 1. Here middle equals left, so the left half is a single element and counts as sorted. That is why the test uses <=.
    • No rotation. [0, 1, 2, 4, 5, 6, 7] with target 6 returns 5. The left half is sorted in every pass, and the method behaves like ordinary binary search.
    • Target at an end. [4, 5, 6, 7, 0, 1, 2] with target 4 returns 0, and with target 2 returns 6. The comparisons with nums[left] and nums[right] are inclusive, so the ends of a sorted half count as inside it.
    • Target not present. [4, 5, 6, 7, 0, 1, 2] with target 3 returns -1.
    • Using left < right as the loop condition. A window of one element would never be checked, so [1] with target 1 would return -1.
    • Strict comparisons at the ends. Writing nums[left] < target would miss a target sitting exactly at left.

    Testing

    • [4, 5, 6, 7, 0, 1, 2] with target 0 gives 4.
    • [4, 5, 6, 7, 0, 1, 2] with target 3 gives -1.
    • [6, 7, 1, 2, 3, 4, 5] with target 7 gives 1.
    • [3, 1] with target 1 gives 1.
    • [5, 1, 3] with target 5 gives 0.
    • [1] with target 0 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