Start learning free

LESSON 99 OF 314 · BINARY SEARCH

Search in Rotated Sorted Array in Go: 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 < len(nums).

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

    GO · BINARY SEARCH

    Search In Rotated Sorted Array in Go, explained

    Problem overview

    The function search receives a slice of distinct integers, nums, and an integer target. The slice was sorted in ascending order and then possibly rotated: its first k elements were moved, in the same 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], and with k = 0 it stays as it was. The function returns the index of target in nums, or -1 if it isn't there.

    In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 isn't present, so the answer is -1. The budget is O(log n) time and O(1) extra space, which rules out scanning the slice and calls for binary search.

    Approach: one half is always sorted

    Plain binary search needs a fully sorted slice: compare the middle element with the target and drop the half that can't hold it. A rotated slice isn't sorted, so a single comparison with the middle tells nothing about which side to keep.

    But the rotation leaves one useful property. The values drop only once, at the rotation point, so that drop falls in at most one of the two halves around middle. The other half rises from its first element to its last. In a sorted half, comparing the target with the half's two ends is enough to know whether the target can be inside it:

    • If the left half, from left to middle, is sorted, and the target lies between nums[left] and nums[middle], keep the left half. Otherwise the target can only be in the right half.
    • If the left half isn't sorted, the right half is. Keep it if the target lies between nums[middle] and nums[right], and otherwise keep the left.

    Every pass drops half of the window, so the loop runs about log₂ n times.

    Here is the search for 7 in [6, 7, 1, 2, 3, 4, 5]. At first left is 0 and right is 6, so middle is 3 and nums[3] is 2. The left half starts with 6, which is bigger than 2, so it isn't sorted, and the right half, [2, 3, 4, 5], is. The target 7 isn't between 2 and 5, so the search moves to the left half with right = 2. Now middle is 1 and nums[1] is 7: the function returns 1.

    Step by step

    1. Declare both ends in one statement: left is 0 and right is len(nums) - 1. Both are inclusive, so the window is everything from left to right.
    2. Loop while left <= right. When they are equal, one element is still left to check.
    3. Compute middle as left + (right-left)/2. Integer division rounds down, and adding half the distance to left avoids the overflow that halving a sum could cause in other languages.
    4. Return middle if nums[middle] == target. After this check, the steps only have to decide which half to drop.
    5. Test whether the left half is sorted: nums[left] <= nums[middle]. With <=, a half with a single element, when left equals middle, counts as sorted.
    6. In the sorted left half, if nums[left] <= target and target < nums[middle], move right to middle - 1. The comparison with nums[middle] is strict, because that element was already checked.
    7. Otherwise move left to middle + 1: the target can't be in the sorted left half.
    8. If the left half isn't sorted, the right half, from middle to right, is.
    9. In the sorted right half, if nums[middle] < target and target <= nums[right], move left to middle + 1.
    10. Otherwise move right to middle - 1: the target can only be in the left half.
    11. Return -1 after the loop. The window is empty, and every index that could hold the target was ruled out.

    The solution in Go

    func search(nums []int, target int) int {
        left, right := 0, len(nums)-1
        for left <= right {
            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
    }
    

    The Go details worth a closer look:

    • Go's while loop. for left <= right { ... } is a for with only a condition. Go has no while keyword.
    • Multiple declaration. left, right := 0, len(nums)-1 declares both variables on one line.
    • Integer division. (right-left)/2 on two ints truncates toward zero. The difference is never negative inside the loop, so it rounds down. Because int is 64 bits on a 64-bit build, even (left+right)/2 would not overflow for a slice of at most 10⁶ elements, but the left + (right-left)/2 form is safe in general.
    • No parentheses around conditions. Go's if doesn't need them, but the braces are required, even for a one-line body.
    • Return values. Every path ends in a return: inside the loop when the target is found, or -1 after it. Go refuses to compile a function with a result type if some path can reach the end without returning.

    Complexity

    Time: O(log n). Every iteration either returns or discards at least half of the window, so at most about log₂ n iterations run, each doing a constant amount of work.

    Space: O(1). Only left, right and middle are kept. The slice is not copied or changed.

    Edge cases and common mistakes

    • One element. [1] with target 1 gives 0, and with target 0 gives -1.
    • Not rotated. [1, 2, 3, 4] with target 4 gives 3. The left half is sorted at every step, and the search behaves like an ordinary binary search.
    • Two elements. [3, 1] with target 1 gives 1. Here left equals middle at the first step, so the "left half is sorted" test must use <=. With a strict <, the left half would count as unsorted, the code would look for the target in the right half and wrongly return -1.
    • Looping while left < right. The last remaining element is then never checked. With [1] and target 1, the loop doesn't run and the function returns -1.
    • Target at the first element. [5, 1, 2, 3, 4] with target 5 gives 0. The first test uses nums[left] <= target, with <=, so the left end of the sorted half is included.
    • Target not present. [4, 5, 6, 7, 0, 1, 2] with target 3 gives -1, once the window empties.
    • Duplicates. The lesson guarantees distinct values. With duplicates, nums[left] <= nums[middle] can't tell a sorted half from a rotated one, and the method would need extra handling.

    Testing

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