Start learning free

LESSON 99 OF 314 · BINARY SEARCH

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

    KOTLIN · BINARY SEARCH

    Search In Rotated Sorted Array in Kotlin, explained

    Problem overview

    The function search receives an IntArray named nums and an integer target. The array held distinct integers in ascending order, and then it was 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 with k = 3 becomes [4, 5, 6, 7, 0, 1, 2]. The function returns the index of target in the rotated array, or -1 if it isn't there, in O(log n) time and O(1) extra space.

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

    Approach

    A loop over the array finds the target in O(n), but O(log n) calls for binary search, which needs an order to exploit. A rotated array is not sorted as a whole, so the usual comparison with the middle element doesn't tell which half holds the target.

    The key idea is that wherever 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 inside at most one half, and the other half rises from end to end. The search works in three moves:

    1. Check whether nums[middle] is the target.
    2. Find which half is sorted by comparing nums[left] with nums[middle].
    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, keep the other one.

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

    Step by step

    1. Set the window. var left = 0 and var right = nums.size - 1. Both ends are inclusive, so the window is everything from left to right. They are vars because the loop moves them.
    2. Loop while (left <= right). With <=, a window of one element is still checked.
    3. Find the middle: val middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance to left never overflows, unlike halving the sum.
    4. Check for a hit: if nums[middle] == target, return middle. This comes first, so the steps below only decide which half to drop.
    5. Is the left half sorted? Test nums[left] <= nums[middle]. Use <=: when left equals middle, the left half is a single element, and one element is sorted.
    6. Target in the sorted left half? If nums[left] <= target && target < nums[middle], set right = middle - 1. The comparison with nums[middle] is strict, because that element was already checked.
    7. Otherwise the target can't be in the sorted left half: set left = middle + 1.
    8. The else branch of the sorted-left test handles the case where the left half isn't sorted. Then the rotation point is in the left half, so everything from middle to right rises.
    9. Target in the sorted right half? If nums[middle] < target && target <= nums[right], set left = middle + 1. This is the same test, mirrored.
    10. Otherwise set right = middle - 1.
    11. After the loop the window is empty and every possible index has been ruled out, so return -1.

    Here is the search for 7 in [6, 7, 1, 2, 3, 4, 5], printing the window on each pass:

    left=0 right=6 middle=3 nums[middle]=2
    left=0 right=2 middle=1 nums[middle]=7
    found at 1
    

    At the first pass, nums[0] = 6 is larger than nums[3] = 2, so the left half isn't sorted and the right half, 2 to 5, is. The target 7 is not between 2 and 5, so the search moves left. The second pass finds it. For the target 0 in [4, 5, 6, 7, 0, 1, 2], the passes show middle as 3, then 5, then 4, and the target is found at index 4.

    The solution in Kotlin

    class Solution {
        fun search(nums: IntArray, target: Int): Int {
            var left = 0
            var right = nums.size - 1
            while (left <= right) {
                val 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
        }
    }
    

    Kotlin details worth knowing:

    • Integer division. / on two Int values truncates, so (right - left) / 2 is a whole number.
    • Overflow. Int is 32 bits and wraps silently. With left = 2000000000 and right = 2100000000, the expression (left + right) / 2 gives -97483648, while left + (right - left) / 2 gives 2050000000. The lesson's arrays are far smaller than that, but the safe form costs nothing.
    • Early return. A return inside the while loop leaves the function at once, so the final return -1 runs only when the loop ends without a hit.
    • Short-circuit &&. Each range test is a pair of comparisons joined by &&, and both must hold for the target to be inside the sorted half.

    Complexity

    Time is O(log n): every pass of the loop halves the window. Extra space is O(1): three integers and no copies of the array.

    Edge cases and common mistakes

    • Using < in nums[left] <= nums[middle]. With two elements, left equals middle, and the left half is one sorted element. With < the code treats it as unsorted. For [3, 1] and target 1, the solution returns 1, but a version with the strict comparison returns -1.
    • A single element. [1] with target 1 gives 0, and with target 0 gives -1.
    • Not rotated. With k = 0 the array is plain sorted. [1, 2, 3, 4, 5] with target 5 gives 4: the left half is always sorted, so this is ordinary binary search.
    • Rotation by one. [5, 1, 2, 3, 4] with target 5 gives 0, and [2, 3, 4, 5, 1] with target 1 gives 4. Both ends of the array can hold the target.
    • Moving a pointer to middle instead of past it. After the hit check, middle is known not to be the target, so the code always moves to middle - 1 or middle + 1. Keeping middle in the window could loop forever.
    • Distinct values. The solution relies on all values being different. With duplicates, nums[left] == nums[middle] can't tell which half is sorted.

    Testing

    Results the solution returns:

    [4, 5, 6, 7, 0, 1, 2], target 0 -> 4
    [4, 5, 6, 7, 0, 1, 2], target 3 -> -1
    [6, 7, 1, 2, 3, 4, 5], target 7 -> 1
    [1], target 1                   -> 0
    [1], target 0                   -> -1
    [3, 1], target 1                -> 1
    [1, 2, 3, 4, 5], target 5       -> 4
    [5, 1, 2, 3, 4], target 5       -> 0
    [2, 3, 4, 5, 1], target 1       -> 4
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free