Start learning free

LESSON 99 OF 314 · BINARY SEARCH

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

    TYPESCRIPT · BINARY SEARCH

    Search In Rotated Sorted Array in TypeScript, explained

    Problem overview

    The method search receives nums, an array of distinct integers that was sorted in ascending order and then possibly rotated, and a number target. A rotation at index k moves the first k elements, in the same order, to the end: [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 nums, or -1 if it is not there. It must run in O(log n) time with O(1) extra space.

    For nums = [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.

    Approach: one half is always sorted

    A linear scan is O(n). Ordinary binary search is O(log n) but needs a sorted array, and a rotated one is only sorted in two pieces. The lesson's key idea is that, whatever the rotation point is, at least one of the two halves around middle 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.

    In a sorted half, comparing target with the half's two ends tells whether it can be inside. So each pass does this:

    1. Check middle itself.
    2. Find which half is sorted.
    3. If target lies within that sorted half, keep it. Otherwise keep the other half.

    Either way, half the window is dropped, so the loop runs about log2 n times.

    Take nums = [6, 7, 1, 2, 3, 4, 5] and target = 7. The first window is indices 0 to 6, and middle is 3, which holds 2. The right half, [2, 3, 4, 5], is sorted and 7 isn't between 2 and 5, so 7 can only be in the left half. The window becomes indices 0 to 2, with middle at 1, which holds 7. The method returns 1.

    Step by step

    1. Set the window with one let: left is 0 and right is nums.length - 1. Both ends are inclusive.
    2. Loop while left <= right. When they are equal, one element is still to check, so <= is needed.
    3. Compute middle as Math.floor(left + (right - left) / 2). Division keeps the fraction in JavaScript numbers (7 / 2 is 3.5), and an index must be whole.
    4. Return middle if it holds the target. This check comes first, so the later 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 half is a single element, which counts as sorted.
    6. If the left half is sorted and target is in it (at least nums[left] and strictly less than nums[middle]), move right to middle - 1.
    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. If target is in the sorted right half (strictly greater than nums[middle] and at most nums[right]), move left to middle + 1.
    10. Otherwise move right to middle - 1.
    11. After the loop, return -1. Every index that could hold the target has been ruled out.

    The solution in TypeScript

    class Solution {
        search(nums: number[], target: number): number {
            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 TypeScript details:

    • Math.floor is required. In TypeScript, number is a double and / never truncates, so (0 + 6) / 2 is fine but (0 + 7) / 2 is 3.5. An index of 3.5 reads undefined from the array instead of failing.
    • No overflow worry. left + (right - left) / 2 is the form that avoids overflow in languages with 32-bit integers. TypeScript numbers don't overflow at these sizes, but the form is still correct.
    • == here. The reference uses == for nums[middle] == target. With two numbers it behaves like ===, which is the form most code prefers because it never converts types.
    • Window state in two variables. The method uses only left, right and middle, which is why the space is constant.

    Complexity

    Time: O(log n). Each pass of the loop drops at least half of the window, so at most about log2 n passes happen, with constant work in each.

    Space: O(1). Only a few numbers are stored.

    Edge cases and common mistakes

    • Strict < when testing the sorted half. With nums[left] < nums[middle], a two-element window such as [3, 1] is treated as having an unsorted left half. Searching for 1 in [3, 1] then returns -1 instead of 1.
    • Using < in the loop condition. A window of one element would never be checked, and a one-element array would fail.
    • Forgetting one end of a range test. The target can equal nums[left] or nums[right], so those comparisons use <=. The comparison with nums[middle] is strict, because middle was already checked.
    • No rotation. With k = 0 the array is plain sorted. The left half is then always sorted, and the method acts as ordinary binary search. For [0, 1, 2, 4, 5, 6, 7] with target 5 it returns 4.
    • Duplicates. The method relies on distinct values. With repeated values, nums[left] <= nums[middle] can't tell which half is sorted, and the lesson's constraints exclude that case.
    • Missing target. It returns -1, as in [1] with target 0.

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