DEV Community

Tanishka V
Tanishka V

Posted on

ASSIGNMENT 20

Search in a Rotated Sorted Array (O(log n) Binary Search)

Searching in a rotated array might look tricky at first β€” but with the right approach, it becomes elegant and efficient πŸ”₯

Let’s break it down πŸ‘‡

πŸ“Œ Problem Statement

You are given a sorted array that has been rotated at some unknown index.

πŸ‘‰ Your task is to find the index of a target element.

⚠️ Constraints:
All elements are distinct
Must run in O(log n) time
If target not found β†’ return -1
πŸ§ͺ Examples
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
πŸ’‘ Key Insight

Even though the array is rotated, one half is always sorted.

πŸ‘‰ At any point:

Either the left half is sorted
Or the right half is sorted

We use this property to apply Binary Search.

🧠 Algorithm Strategy
Find mid
Check which half is sorted:
If nums[low] <= nums[mid] β†’ Left half is sorted
Else β†’ Right half is sorted
Decide where target lies:
If target is in sorted half β†’ search there
Else β†’ search other half
πŸ”„ Step-by-Step Logic
Case 1: Left Half is Sorted
nums[low] <= nums[mid]

If:

nums[low] <= target < nums[mid]

β†’ Search left

Else β†’ Search right
Case 2: Right Half is Sorted
nums[mid] < nums[high]

If:

nums[mid] < target <= nums[high]

β†’ Search right

Else β†’ Search left
πŸ’» Python Implementation
def search(nums, target):
low, high = 0, len(nums) - 1

while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
    return mid

# Left half sorted
if nums[low] &lt;= nums[mid]:
    if nums[low] &lt;= target &lt; nums[mid]:
        high = mid - 1
    else:
        low = mid + 1

# Right half sorted
else:
    if nums[mid] &lt; target &lt;= nums[high]:
        low = mid + 1
    else:
        high = mid - 1
Enter fullscreen mode Exit fullscreen mode

return -1

Enter fullscreen mode Exit fullscreen mode




Example usage

nums = [4,5,6,7,0,1,2]
target = 0
print(search(nums, target))
🧾 Output
4
πŸ” Dry Run (Quick Insight)

For:

[4,5,6,7,0,1,2], target = 0
Mid = 7 β†’ left sorted
Target not in left β†’ move right
Eventually find 0 at index 4
⚑ Complexity Analysis
Metric Value
Time Complexity O(log n)
Space Complexity O(1)

Top comments (0)