BackendML

Search in Rotated Sorted Array

Medium2 min read
The Search in Rotated Sorted Array problem requires finding the index of a target value in a sorted array that has been rotated.

Problem

Given an integer array nums that was originally sorted in ascending order and then possibly rotated, along with an integer target, return the index of target if it exists. Otherwise, return -1.

You may assume that all elements in the array are distinct. The algorithm should run in O(log n) time.

Example(s)

Consider the following example(s) to understand the expected input and output.

Input

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

Output

4 

Solution

This solution uses a modified Binary Search. Even though the array is rotated, at least one half of the array is always sorted.

For each middle element, we first check whether the target is present at mid. If it is, we return the index immediately.

If the target is not found, we determine which half of the current search range is sorted. If the left half is sorted, we check whether the target lies within its range. If it does, we recursively search the left half; otherwise, we search the right half.

If the right half is sorted, we similarly check whether the target lies within its range. If it does, we recursively search the right half; otherwise, we search the left half.

The process continues recursively until the target is found or the search range becomes empty.
class Solution {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            }
            
            // Check if the left half is normally sorted
            if (nums[left] <= nums[mid]) {
                // Check if the target lies within this sorted left half
                if (target >= nums[left] && target < nums[mid]) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            } 
            // Otherwise, the right half must be normally sorted
            else {
                // Check if the target lies within this sorted right half
                if (target > nums[mid] && target <= nums[right]) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return -1;
    }
}

Complexity

Each recursive call eliminates approximately half of the remaining search space, resulting in a time complexity of O(log n).

Because the solution uses recursion, the extra space complexity is O(log n) due to the recursive call stack.

Comments

No comments yet. Ask a question or share what helped.