SEARCH IN ROTATED SORTED ARRAY

 

Search in Rotated Sorted Array – Modified Binary Search

Introduction

In this problem, we are given a sorted array that has been rotated at some unknown index. Our task is to find a target element in this array in O(log n) time.

Since the array is not fully sorted anymore, a normal binary search will not work directly. So we modify the binary search logic.

Problem Statement

Given:

  • A sorted array that is rotated

  • A target value

Return:

  • Index of the target if found

  • Otherwise return -1

Example

Input:

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

Output:

4

Solution Code

class Solution {
    public int search(int[] nums, int target) {
        int start = 0, end = nums.length - 1;

        while (start <= end) {
            int mid = start + (end - start) / 2;

            if (nums[mid] == target) return mid;

            
            if (nums[mid] >= nums[start]) {
                if (target >= nums[start] && target < nums[mid]) {
                    end = mid - 1;
                } else {
                    start = mid + 1;
                }
            } 
            
            else {
                if (target > nums[mid] && target <= nums[end]) {
                    start = mid + 1;
                } else {
                    end = mid - 1;
                }
            }
        }

        return -1;
    }
}

Approach Used: Modified Binary Search

Idea

Even though the array is rotated:

  • At least one half will always be sorted

We use this property to decide where to search.

How It Works

  1. Find mid

  2. Check if nums[mid] == target = return index

  3. Identify sorted half:

    • If nums[start] <= nums[mid] = left half is sorted

    • Else = right half is sorted

  4. Decide where target lies:

    • If target is inside sorted half = search there

    • Else = search in the other half

Why This Approach Was Chosen

  • Maintains O(log n) time

  • Efficient even after rotation

  • Uses properties of sorted array

Alternative Approach

  • Linear Search

    for(int i = 0; i < nums.length; i++)
    

     Time Complexity: O(n)

Why not used?
Does not meet the required O(log n) constraint

Time and Space Complexity

  • Time Complexity: O(log n)

  • Space Complexity: O(1)

Important Observation

  • One half of the array is always sorted

  • Rotation does not completely destroy sorted order

  • That’s the key idea behind solving this

Edge Cases

  • Array with one element

  • Target not present

  • Rotation at index 0 (normal sorted array)

Conclusion

By slightly modifying binary search, we can efficiently search in a rotated sorted array. The key insight is identifying the sorted half in each step and narrowing the search accordingly.

Comments

Popular posts from this blog

THE DELIVERY MAN

EC2 LAUNCHING

SORT A LINKED LIST USING MERGE SORT