Start learning free

LESSON 377 OF 667 · BINARY SEARCH

Search in Rotated Sorted Array in C++: Binary Search, O(log n)

Practice O(log n) Read the full explanation

You get an integer target and a vector 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.size().

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

    C++ · BINARY SEARCH

    Search In Rotated Sorted Array in C++, explained

    Problem overview

    The method search receives a vector<int> named nums of distinct integers and an integer 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 method returns the index of target, or -1 when it isn't there.

    In [4, 5, 6, 7, 0, 1, 2], the target 0 is at index 4, and the target 3 is missing, so the answer is -1. In [6, 7, 1, 2, 3, 4, 5], the target 7 is at index 1. The statement asks for O(log n) time and O(1) extra space, with up to a million elements.

    Approach: one half is always sorted

    A linear scan finds the target in O(n), which ignores the sorted structure. Plain binary search needs a fully sorted vector, and a rotated vector isn't one: the values rise, drop once at the rotation point, then rise again.

    The key observation is that if you look at the middle element, at least one of the two halves around it is sorted. The values drop only once, at the rotation point, so the drop falls in at most one half, and the other half rises from end to end.

    That is enough to keep halving the search window:

    1. Check the middle element. If it is the target, return its index.
    2. Work out which half is sorted. If nums[left] <= nums[middle], the left half is sorted. Otherwise the right half is.
    3. In a sorted half, two comparisons with its ends tell you whether the target can be in it. If it can, keep that half. If not, the target can only be in the other half, sorted or not, so keep that one.

    Each pass throws away half of the window, so the loop runs about log2 n times.

    For example, in [6, 7, 1, 2, 3, 4, 5] with target 7, the middle element is nums[3] = 2. The half from the middle to the end, [2, 3, 4, 5], is sorted, and 7 is not between 2 and 5. So 7 can only be in the left part, and the search continues there.

    Step by step

    1. Declare left and right as ints on one line: 0 and nums.size() - 1. Both ends are inclusive: the window is everything from left to right.
    2. Loop while left <= right. Use <=, because when the two are equal one element is still unchecked.
    3. Compute middle as left + (right - left) / 2. Integer division rounds down, and adding half the distance to left can't overflow the way (left + right) / 2 could for very large indices.
    4. Return middle if nums[middle] == target. After this check, the other steps only decide which half to drop.
    5. Test whether the left half is sorted: nums[left] <= nums[middle]. The <= matters: when left equals middle, the left half is one element, and one element is sorted.
    6. Inside it, test whether the target lies in that half: nums[left] <= target && target < nums[middle]. The upper bound is strict because nums[middle] was already checked. If so, right = middle - 1.
    7. Otherwise move left = middle + 1: the target isn't in the sorted left half, so it can only be in the right one.
    8. In the outer else, the left half isn't sorted, so the right half, from middle to right, is.
    9. Test whether the target lies in the right half: nums[middle] < target && target <= nums[right]. If so, left = middle + 1.
    10. Otherwise 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 C++

    class Solution {
    public:
        int search(vector<int> &nums, int target) {
            int left = 0, right = nums.size() - 1;
            while (left <= right) {
                int 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 C++ details worth knowing:

    • right is signed on purpose. nums.size() is unsigned, but the result of nums.size() - 1 is stored in an int. Searches like this one move boundaries with middle - 1 and middle + 1, and the usual loop test left <= right relies on ordinary signed arithmetic. With unsigned variables, 0 - 1 would wrap to a huge number instead of -1, and a bound like that could send the loop off the end of the vector.
    • One declaration, two variables. int left = 0, right = nums.size() - 1; declares two ints, each with its own initial value.
    • The vector is a reference. vector<int> &nums avoids copying up to a million elements. The search only reads it.
    • Integer division of two non-negative ints truncates, so (right - left) / 2 rounds down.

    Tracing the examples

    With nums = [4, 5, 6, 7, 0, 1, 2] and target = 0, the windows are:

    leftrightmiddlenums[middle]What happens
    0637left half is sorted (4 to 7), 0 is not in it, so left = 4
    4651left half [0, 1] is sorted and 0 is in it, so right = 4
    4440found, return 4

    With target = 3 the first two windows are the same. In the first, 3 is not in 4 to 7, so left = 4. In the second, the left half [0, 1] doesn't contain 3, so left = 6. The last window, left = 6, right = 6, has middle 6 and nums[6] = 2, which is not 3, and the window then empties, so the result is -1.

    With nums = [6, 7, 1, 2, 3, 4, 5] and target = 7, the first window has middle = 3 and nums[3] = 2. The left half is not sorted, the right half [2, 3, 4, 5] is, and 7 is not in it, so right = 2. The window left = 0, right = 2 has middle = 1 and nums[1] = 7: found, return 1.

    Complexity

    Time is O(log n). Every pass either returns or drops at least half of the window, and each pass does a constant number of comparisons.

    Extra space is O(1). The search uses three integers and no recursion.

    Edge cases and common mistakes

    • Not rotated. With k = 0 the vector is plain sorted, the left half is always the sorted one, and the code is ordinary binary search. [1, 2, 3, 4, 5] with target 5 returns 4.
    • One element. [1] with target 1 returns 0, and with target 0 returns -1.
    • Two elements. [3, 1] with target 1 returns 1, and [2, 1] with target 2 returns 0. This is the case that breaks a strict comparison: here left equals middle at index 0, and the left half must count as sorted.
    • Using < instead of <= in nums[left] <= nums[middle]. When left == middle, the half is wrongly treated as unsorted. With the strict version, searching for 1 in [3, 1] returns -1 instead of 1, and so does searching for 1 in [2, 1].
    • Making the target test strict at both ends. nums[left] can be the target, so the lower bound is <=. Only the end next to middle is strict, because middle was already checked.
    • Duplicates. This solution relies on the values being distinct. With duplicates, nums[left] == nums[middle] no longer proves the left half is sorted, and the search needs extra handling.
    • Target absent. The target 3 in [4, 5, 6, 7, 0, 1, 2] is not in the vector, and the loop ends with the window empty, giving -1.
    Keep going with C++650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free