Start learning free

LESSON 381 OF 671 · BINARY SEARCH

Search in Rotated Sorted Array in Java: Binary Search in O(log n)

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

    JAVA · BINARY SEARCH

    Search In Rotated Sorted Array in Java, explained

    Problem overview

    The method search receives an int[] nums of distinct integers and an int target. The array 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 if it is not there. It must run in O(log n) time with O(1) extra space.

    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.

    Approach: one half is always sorted

    A linear scan solves the problem in O(n), but with up to a million elements the statement wants binary search. Plain binary search needs a fully sorted array, and a rotated array is not sorted: it rises, drops once at the rotation point, and rises again.

    The idea of the lesson is that around any middle, at least one of the two halves is sorted. The values drop only once, so the drop lies in at most one half, and the other half rises from end to end. For a sorted half, two comparisons with its ends tell whether target can be inside it:

    • If the left half (left to middle) is sorted, target is in it exactly when nums[left] <= target < nums[middle].
    • Otherwise the right half is sorted, and target is in it exactly when nums[middle] < target <= nums[right].

    If the target is in the sorted half, keep that half. If not, keep the other one. Either way the window halves, which gives O(log n).

    Trace for nums = [6, 7, 1, 2, 3, 4, 5] and target = 7:

    leftrightmiddlenums[middle]What happens
    0632the left half is 6, 7, 1, 2, which is not sorted; the right half 2 to 5 is sorted and does not hold 7, so right moves to 2
    0217equals the target: return 1

    Step by step

    1. Set the window. left = 0 and right = nums.length - 1. Both ends are inclusive.
    2. Loop while left <= right. With <=, a window of one element still gets checked.
    3. Find the middle. int middle = left + (right - left) / 2; Integer division rounds down. Adding half the distance to left cannot overflow, unlike halving the sum.
    4. Check for the target. If nums[middle] == target, return middle. This comes first, so the rest only decides which half to drop.
    5. Is the left half sorted? Test nums[left] <= nums[middle]. Use <=: when left equals middle, the half is one element, and one element is sorted.
    6. Inside a sorted left half. If nums[left] <= target && target < nums[middle], the target is there, so right = middle - 1. The comparison with nums[middle] is strict, since that element was already checked.
    7. Otherwise the target is not in the sorted left half, so left = middle + 1.
    8. Else, the right half is sorted. If nums[middle] < target && target <= nums[right], the target is there, so left = middle + 1.
    9. Otherwise the target can only be in the left half: right = middle - 1.
    10. After the loop the window is empty and the target was not found, so return -1.

    The solution in Java

    class Solution {
        public int search(int[] nums, int target) {
            int left = 0, right = nums.length - 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 Java details worth a closer look:

    • Declaring two ints at once. int left = 0, right = nums.length - 1; declares both in one statement.
    • Integer division. (right - left) / 2 on two int values drops the fraction, so the middle of an even-length window is the lower of the two middle positions.
    • Why not (left + right) / 2. In Java, int arithmetic wraps silently on overflow. With left = 1500000000 and right = 2000000000, (left + right) / 2 gives -397483648, while left + (right - left) / 2 gives 1750000000. Arrays here are at most a million long, so the sum fits, but this form is a habit worth keeping.
    • Returning from inside a loop. The return middle; ends the method at once. The final return -1; is needed because the compiler rejects a method that could reach its end without returning an int.
    • Plain int comparisons. The elements are primitives, so == and <= compare values directly.

    Complexity

    Time: O(log n). Each pass of the loop discards at least half of the window, so the loop runs about log2 of n times, with constant work per pass.

    Space: O(1). The method keeps three integers, left, right and middle, and builds nothing.

    Edge cases and common mistakes

    • One element. [1] with target 1 gives 0, and with target 0 gives -1.
    • Using left < right. With a window of one element, the loop would never check it. A version with that loop condition returns -1 for [1] with target 1, and also for [3, 1] with target 1.
    • Two elements. In [3, 1] the target 1 is found at index 1. When middle equals left, the left half has one element, and the <= in nums[left] <= nums[middle] correctly treats it as sorted.
    • An array that wasn't rotated. [1, 2, 3, 4, 5] with target 4 gives 3. Rotation at k = 0 is allowed, and then the left half is always the sorted one.
    • Target at the end of the range. [1, 3, 5] with target 5 gives 2. The comparisons include nums[left] and nums[right] through <=, so the ends of a sorted half count as inside it.
    • Dropping middle twice. Because the code already returned when nums[middle] was the target, the strict < against nums[middle] is right, and moving to middle - 1 or middle + 1 always shrinks the window.
    • Duplicates. The method relies on distinct values. With repeated values, nums[left] <= nums[middle] would no longer prove that the left half is sorted. The statement rules duplicates out.

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