Start learning free

LESSON 99 OF 314 · BINARY SEARCH

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

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

    RUST · BINARY SEARCH

    Search In Rotated Sorted Array in Rust, explained

    Problem overview

    The function search receives a vector of distinct integers, nums, and a target. The vector 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]. The function returns the index of target, or -1 if it isn't there, in O(log n) time and O(1) space.

    In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is missing, so the answers are 4 and -1. In [6, 7, 1, 2, 3, 4, 5], the target 7 is at index 1.

    Approach: one half is always sorted

    A linear scan works in O(n), but the problem asks for O(log n), which means binary search. A plain binary search assumes the whole vector is sorted, and a rotated one isn't. On [4, 5, 6, 7, 0, 1, 2] with target 0, a plain search looks at the middle value 7, sees that 7 is bigger than 0, and discards the right half, where 0 actually is. It returns -1.

    The key observation is that the values drop only once, at the rotation point. So around any middle, the drop falls into at most one of the two halves, and the other half is sorted from end to end. For a sorted half, two comparisons with its ends tell whether target can be in it. If it can, keep that half; otherwise, keep the other one. Either way, half of the window is discarded, so there are about log₂ n passes.

    The test for a sorted left half is nums[left] <= nums[middle]. If it fails, the right half, from middle to right, is the sorted one.

    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, the left half [4, 5, 6, 7] is sorted and 0 isn't between 4 and 7, so left moves to 4. In the second pass the window is [0, 1, 2], which is sorted, and 0 is at least nums[left] and smaller than nums[middle], so right moves to 4. The third pass finds 0 at index 4.

    Step by step

    1. Declare left and right as mutable variables: 0 and nums.len() - 1. Both ends are inclusive, and the vector is never empty, so the subtraction is safe.
    2. Loop while left <= right. When they are equal, one element is still unchecked.
    3. Compute middle as left + (right - left) / 2. Integer division already rounds down, and this form can't overflow, unlike halving left + right.
    4. Return middle as i32 if nums[middle] equals target. The cast converts the usize index to the function's i32.
    5. Test whether the left half is sorted: nums[left] <= nums[middle]. The <= covers the case where left equals middle, a half of one element.
    6. In a sorted left half, if nums[left] <= target and target < nums[middle], the target is inside it: set right to middle - 1.
    7. Otherwise drop the left half: set left to middle + 1.
    8. The else of the outer test: the left half isn't sorted, so the right half is.
    9. In a sorted right half, if nums[middle] < target and target <= nums[right], the target is inside it: set left to middle + 1.
    10. Otherwise the target can only be in the left half: set right to middle - 1.
    11. After the loop, every index has been ruled out, so end the function with -1.

    The solution in Rust

    impl Solution {
        fn search(nums: Vec<i32>, target: i32) -> i32 {
            let mut left = 0;
            let mut right = nums.len() - 1;
            while left <= right {
                let middle = left + (right - left) / 2;
                if nums[middle] == target {
                    return middle as i32;
                }
                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;
                    }
                }
            }
            -1
        }
    }
    

    The Rust details worth a closer look:

    • usize indexes. left and right get the type usize from nums.len() - 1 and from indexing. A usize can't be negative, so middle - 1 must never be computed when middle is 0. Both places that do it are safe: in the first, nums[left] < nums[middle] holds (the target is at least nums[left] and smaller than nums[middle]), so middle is past left; in the second, the unsorted left half means nums[left] > nums[middle], which again puts middle past left.
    • The cast on return. middle as i32 converts a usize into an i32. The vector has at most a million elements, so the value always fits. A cast between integer types never panics; it truncates silently if the value doesn't fit.
    • left + (right - left) / 2. Since right >= left inside the loop, right - left can't underflow.
    • The last expression. -1 without a semicolon is the function's value when the loop finishes without a return.
    • Indexing is checked. An out-of-range index panics rather than reading garbage, and the window logic keeps every index inside the vector.

    Complexity

    Time: O(log n). Each pass of the loop discards at least half of the window, so a vector of a million elements needs about 20 passes.

    Space: O(1). The function keeps three indexes and never copies the vector.

    Edge cases and common mistakes

    • A vector that wasn't rotated. [1, 2, 3, 4, 5] with target 4 gives 3. The left half is always sorted, and the search behaves like a normal binary search.
    • A single element. [1] with target 1 gives 0, and with target 0 gives -1: the window becomes empty after one pass.
    • Two elements. [3, 1] with target 1 gives 1. Here left equals middle, and the left half is a single element, which counts as sorted because of the <=. With a strict <, the test would fail, the code would go to the other branch, and middle - 1 would underflow the usize because middle is 0.
    • The target at an end. [5, 1, 3] with target 5 gives 0, and [4, 5, 6, 7, 0, 1, 2] with target 2 gives 6. The comparisons with nums[left] and nums[right] are inclusive on the end that isn't middle, so these are found.
    • Using a plain binary search. It gives -1 for target 0 in [4, 5, 6, 7, 0, 1, 2], target 7 in [6, 7, 1, 2, 3, 4, 5] and target 1 in [3, 1], even though all three are present.
    • Using left < right as the loop condition. The loop would stop with one unchecked element left, and a target there would be reported as missing: [1] with target 1 would return -1.
    • Inclusive and exclusive comparisons. The target is compared with nums[middle] strictly because middle was already checked for equality. The comparisons with the far end of the sorted half are inclusive, because that end hasn't been checked.

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