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] <= nums[mid]:
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
# Right half sorted
else:
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
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)