Taro Logo

Search in Rotated Sorted Array

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+37
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.8K views
Topics:
ArraysBinary Search

There is an integer array nums sorted in ascending order (with distinct values).

Prior to being passed to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

Given the array nums after the possible rotation and an integer target, return the index of target if it is in nums, or -1 if it is not in nums.

You must write an algorithm with O(log n) runtime complexity.

Example 1:

Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4

Example 2:

Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1

Example 3:

Input: nums = [1], target = 0
Output: -1

Constraints:

  • 1 <= nums.length <= 5000
  • -104 <= nums[i] <= 104
  • All values of nums are unique.
  • nums is an ascending array that is possibly rotated.
  • -104 <= target <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Are all the integers in the array distinct, or should I expect duplicate values?
  2. What should be returned if the target value is not found in the array?
  3. What is the expected range of the values inside the array and the target?
  4. How should I handle empty or null array inputs?
  5. Can I assume the array was originally sorted in strictly ascending order?

Brute Force Solution

Approach

Imagine you have a row of items that has been split and shifted around, and you need to find a specific item hidden inside. The brute force approach simply checks every single item one by one until you find the one you are looking for.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first item in the row.
  2. Ask yourself if this item is the one you want.
  3. If it is the correct item, you are done and you can celebrate finding it.
  4. If it is not the correct item, politely move on to the next item right beside it.
  5. Repeat this process of checking and moving forward for every single item in the row, without skipping any of them.
  6. If you check the very last item and still have not found what you are looking for, conclude that the item is definitely not in the row.

Code Implementation

def search_rotated_array(nums, target):
    # We iterate through every element because the array is rotated and unsorted for a linear scan
    for current_index in range(len(nums)):

        # Check current element against target to see if we found a match
        if nums[current_index] == target:
            return current_index

    # Exhausted all elements without finding the target so return negative one
    return -1

Big(O) Analysis

Time Complexity
O(n) – The brute force approach examines each of the n items in the rotated sorted array sequentially one by one without skipping any elements. In the worst-case scenario where the target is at the very end or completely absent, we perform a single check for every single element in the array. This linear scanning process totals exactly n individual operations. Therefore, the time complexity simplifies to O(n).
Space Complexity
O(1) – The provided plain English solution relies entirely on checking items one by one in place without gathering them into a temporary pile or utilizing auxiliary data structures. It only maintains a few primitive tracking variables to iterate through the row of items, regardless of the input size N. Therefore, the extra memory required remains constant and does not scale with the number of elements.

Optimal Solution

Approach

Even though the sequence of numbers has been shifted and broken, we can still use a clever guessing game by always looking right at the middle. Because one half of any section is guaranteed to be in normal order, we can easily figure out which side our target must be hiding in.

Here's how the algorithm would work step-by-step:

  1. Look at the exact middle of the current section to see if your target is hiding right there.
  2. Figure out which side of the middle is acting normally and which side has the weird broken shift.
  3. Check if your target falls neatly within the normal side's range.
  4. If it falls within that normal range, throw away the other side completely and focus only on the normal side.
  5. If it does not fall within that normal range, throw away the normal side instead and focus entirely on the other side.
  6. Repeat this process of checking the middle and halving your search space until you either find your target or run out of numbers.

Code Implementation

def search(nums_array, target_value):
    left_pointer = 0
    right_pointer = len(nums_array) - 1

    while left_pointer <= right_pointer:
        middle_index = (left_pointer + right_pointer) // 2

        if nums_array[middle_index] == target_value:
            return middle_index

        # Identify if the left half is normally sorted to determine search boundaries.
        if nums_array[left_pointer] <= nums_array[middle_index]:

            # Check if target lies within the sorted left side to eliminate the other half.
            if nums_array[left_pointer] <= target_value < nums_array[middle_index]:
                right_pointer = middle_index - 1
            else:
                left_pointer = middle_index + 1
        else:
            # Check if target lies within the sorted right side to eliminate the other half.
            if nums_array[middle_index] < target_value <= nums_array[right_pointer]:
                left_pointer = middle_index + 1
            else:
                right_pointer = middle_index - 1

    return -1

Big(O) Analysis

Time Complexity
O(log n) – The algorithm uses a modified binary search where the input size n is repeatedly halved at each step by examining the middle element. In each iteration, we determine which half of the array is normally sorted and use it to decide whether to discard the left or right half entirely. Since we divide the remaining search space in half with every check, the number of operations grows logarithmically. This halving process results in approximately log base 2 of n steps, which simplifies to O(log n).
Space Complexity
O(1) – The algorithm relies entirely on a fixed number of pointer variables, such as left, right, and mid, to track the current search boundaries. Because these variables occupy a constant amount of memory regardless of the input size N, no additional data structures or recursive call stacks are created. Therefore, the extra memory used remains completely constant, resulting in an auxiliary space complexity of O(1).

Edge Cases

Empty or null input array
How to Handle:
Check for null or empty arrays at the start and return negative one immediately.
Array with a single element matching or not matching the target
How to Handle:
The binary search bounds check the single element directly and return its index or negative one.
Array with two elements, either rotated or not
How to Handle:
The conditional checks correctly identify which half is sorted even with minimal length.
Target is located at the exact pivot point where the rotation occurs
How to Handle:
Standard binary search conditions correctly evaluate the middle element against the target regardless of rotation.
Array is not actually rotated, meaning the rotation count is zero
How to Handle:
The left-sorted check naturally falls through to standard binary search logic when the entire array is ordered.
Target is smaller than the minimum or larger than the maximum value in the array
How to Handle:
The boundary comparisons fail the range checks for the sorted half and correctly shift the search window.
Large scale inputs approaching maximum constraints
How to Handle:
The logarithmic time complexity ensures the solution scales efficiently without exceeding time limits.
Inputs containing negative numbers and zero values
How to Handle:
Using standard integer comparisons handles negative numbers, zeros, and positive numbers uniformly.
0/75 completed