Start learning free

LESSON 381 OF 671 · BINARY SEARCH

Search in Rotated Sorted Array in JavaScript: 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

    JAVASCRIPT · BINARY SEARCH

    Search In Rotated Sorted Array in JavaScript, explained

    Problem overview

    The method search(nums, target) receives an array of distinct integers that 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 in the rotated array, or -1 when it isn't there. The statement asks for O(log n) time and O(1) extra space.

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

    Approach: binary search, one sorted half at a time

    A linear scan finds the target in O(n), which is too slow for the requested budget. Ordinary binary search needs a fully sorted array, and a rotated one is not. But it is sorted in two pieces, and that is enough.

    The key observation: whichever index middle you pick, at least one of the two halves around it is sorted. The values drop only once, at the rotation point, and that drop lies in at most one of the halves. The other half rises from end to end.

    So each pass of the loop does this:

    1. Check nums[middle] against the target and return if it matches.
    2. Find a sorted half: 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 whether the target can be inside. If it can, keep that half. If not, the target can only be in the other half, so keep that one.

    Every pass discards 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]. The first middle is index 3, holding 2. The left value 6 is larger than 2, so the left half is not sorted and the right half, 2 to 5, is. The target 7 is not between 2 and 5, so the search moves left with right = 2. The next middle is index 1, which holds 7, and the function returns 1.

    The unsuccessful search for 3 in [4, 5, 6, 7, 0, 1, 2] goes through the windows 0 to 6, then 4 to 6, then 6 to 6, and returns -1 once the window is empty.

    Step by step

    1. Declare left and right with one let: the first index, 0, and the last one, nums.length - 1. Both ends are inclusive.
    2. Loop while left <= right. When they are equal, one element is still to check.
    3. Compute middle as left + (right - left) / 2, wrapped in Math.floor because the division can produce a fraction and an index must be whole.
    4. Return middle if nums[middle] equals target. After this check, the rest only decides which half to drop.
    5. Test whether the left half is sorted with nums[left] <= nums[middle]. The <= matters: when left equals middle, that half is one element, and one element is sorted.
    6. Left half sorted: the target is inside it when nums[left] <= target and target < nums[middle]. Then drop the right half with right = middle - 1.
    7. Otherwise drop the left half with left = middle + 1.
    8. Left half not sorted: then the right half, from middle to right, is.
    9. Right half sorted: the target is inside it when nums[middle] < target and target <= nums[right]. Then drop the left half with left = middle + 1.
    10. Otherwise drop the right half with right = middle - 1.
    11. After the loop, return -1: every index that could hold the target has been ruled out.

    The solution in JavaScript

    class Solution {
        search(nums, target) {
            let left = 0, right = nums.length - 1;
            while (left <= right) {
                let middle = Math.floor(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;
        }
    }
    

    Some JavaScript details worth knowing:

    • Division gives a fraction. In JavaScript, 7 / 2 is 3.5, not 3, and nums[3.5] is undefined. Math.floor turns the offset into a whole number. When the midpoint is computed as left + (right - left) / 2, it is always between left and right.
    • No integer overflow to worry about. JavaScript numbers are doubles, so left + right would be exact for any array length here. Writing left + (right - left) / 2 is still a common habit, and it works the same everywhere.
    • == in the match test. The reference compares with ==, which converts types when they differ, so a target of '0' would match the number 0. With two numbers, == and === give the same answer. The range tests with <= and < also convert strings to numbers. Prefer === in your own code.
    • Comparison operators on numbers. The comparisons nums[left] <= target and target < nums[middle] are ordinary numeric comparisons, which work for negative values too.

    Complexity

    Time: O(log n). Each pass of the loop discards at least half of the window, and every pass does a constant number of comparisons. An array of a million elements needs about 20 passes.

    Space: O(1). The function keeps three indices and no extra arrays.

    Edge cases and common mistakes

    • A single element. [1] with target 1 gives 0, and with target 0 gives -1.
    • Two elements. Here left equals middle, so the left "half" is one element. [3, 1] with target 1 returns 1. If the sorted-half test used < instead of <=, the same input would return -1, because the code would wrongly treat the left half as unsorted.
    • No rotation. With k = 0 the array is plain sorted, and the same code works: [0, 1, 2, 4, 5, 6, 7] with target 5 gives 4.
    • Target at the first or last position. [5, 1, 3] with target 5 gives 0, and [2, 3, 4, 5, 1] with target 1 gives 4.
    • A target that is not there. Both ends of the sorted half are compared, so a value outside the array's range, or one that falls in the gap, ends with left past right and returns -1.
    • Making the comparisons strict at the wrong end. nums[middle] was already checked, so it is excluded from the range tests (target < nums[middle] and nums[middle] < target), while the ends nums[left] and nums[right] are included.
    • Using < right in the loop. The condition must be left <= right, otherwise a window with one element is never examined.
    • Assuming distinct values. The statement guarantees them. With duplicates, nums[left] <= nums[middle] can no longer tell which half is sorted, and this approach would need changes.

    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, -3, 0, 9, -9, -7], target = -9 gives 4.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free