Start learning free

LESSON 99 OF 314 · BINARY SEARCH

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

    C# · BINARY SEARCH

    Search In Rotated Sorted Array in C#, explained

    Problem overview

    The method Search receives an int[] called nums and an integer target. The array holds distinct values that were 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.

    Approach: binary search that finds the sorted half

    A linear scan is O(n). Plain binary search is O(log n) but needs a fully sorted array. A rotated array is not sorted, but it is two sorted runs glued together, and that is enough.

    The key fact: pick any middle index. The values drop only once in the whole array, at the rotation point, so that drop lies in at most one of the two halves around the middle. The other half rises from end to end, so it is sorted. In a sorted range, comparing target with the two ends tells whether it can be inside. That gives a rule for each pass:

    1. If nums[middle] is the target, return middle.
    2. Find which half is sorted by comparing nums[left] with nums[middle].
    3. If the target lies within the sorted half's range, keep that half. Otherwise keep the other half.

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

    Take {4, 5, 6, 7, 0, 1, 2} and target 0. The first window is indices 0 to 6, with middle = 3 (value 7). The left half 4, 5, 6, 7 is sorted and 0 is not between 4 and 7, so left becomes 4. The window is now indices 4 to 6, with middle = 5 (value 1). The left half 0, 1 is sorted, and 0 is between 0 and 1, so right becomes 4. The window is the single index 4, with middle = 4, and its value is 0: return 4.

    The same idea works whether or not the array was actually rotated. With k = 0 the left half is always the sorted one, and the method behaves like an ordinary binary search.

    Step by step

    1. Declare left = 0 and right = nums.Length - 1. Both ends are inclusive.
    2. Loop while left <= right. Use <=: when the two are equal, one element is still unchecked.
    3. Compute middle = left + (right - left) / 2. Integer division rounds down, and adding half the distance to left, rather than halving left + right, can't overflow.
    4. Return middle if nums[middle] == target. After this check, the later steps only decide which half to drop.
    5. Test nums[left] <= nums[middle]. If true, the left half is sorted. The <= matters: when left == middle, the half is one element, which is sorted.
    6. Left half sorted: 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 set left = middle + 1: the target can only be in the other half.
    8. Left half not sorted: then the right half, from middle to right, is. If nums[middle] < target && target <= nums[right], set left = middle + 1.
    9. Otherwise set right = middle - 1.
    10. After the loop, the window is empty: return -1.

    The solution in C#

    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;
        }
    }
    

    C# details worth knowing:

    • Integer division truncates. (right - left) / 2 on two int values discards the fraction, so middle is the lower of the two central indices when the window has an even length.
    • Overflow wraps silently. int arithmetic is unchecked by default. For arrays of up to a million elements (left + right) / 2 is fine, but the left + (right - left) / 2 form stays correct for any array length.
    • Several variables in one declaration. int left = 0, right = nums.Length - 1; declares two ints, each with its own initial value.
    • No exception on a miss. The method returns -1 as a result value, a convention like Array.IndexOf, instead of throwing.

    Complexity

    Time: O(log n). Every pass either returns or halves the window, so there are at most about log2 n passes.

    Space: O(1). Only left, right and middle are kept.

    Edge cases and common mistakes

    • Not rotated. With k = 0 the array is plain sorted, and the left half is always the sorted one. Search(new[] {0, 1, 2, 4, 5, 6, 7}, 5) returns 4.
    • One element. {1} with target 1 returns 0, and with target 0 returns -1.
    • Two elements. {1, 3} with target 3 returns 1. Here middle equals left, which is why nums[left] <= nums[middle] must use <=.
    • Target at the rotation point. For {6, 7, 1, 2, 3, 4, 5} and target 7, the answer is 1.
    • Target absent. {4, 5, 6, 7, 0, 1, 2} with target 3 returns -1.
    • Using < in the sorted-half test. A single-element half is then taken for an unsorted one, and the search goes to the wrong side.
    • Looping with left < right. The last remaining element would never be checked.

    Testing

    • {4, 5, 6, 7, 0, 1, 2} with target 0 gives 4.
    • {4, 5, 6, 7, 0, 1, 2} with target 3 gives -1.
    • {6, 7, 1, 2, 3, 4, 5} with target 7 gives 1.
    • {1} with target 0 gives -1.
    • {1, 3} with target 3 gives 1.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free