This problem is a classic variation of Binary Search, where the array is sorted but rotated at some unknown pivot.
๐ Problem Statement
You are given a sorted array that has been rotated at an unknown index.
Given a target value, return its index if found, otherwise return -1.
The solution must run in O(log n) time.
๐ 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
๐ง Intuition
Even though the array is rotated, one key property still holds:
๐ At least one half of the array is always sorted.
We can use this property to decide where to search.
๐ Approach (Modified Binary Search)
Step-by-Step:
- Initialize:
low = 0high = n - 1
- While
low <= high:
- Find
mid
If
nums[mid] == targetโ returnmidCheck which half is sorted:
-
If left half is sorted (
nums[low] <= nums[mid]):- If target lies in this range โ search left
- Else โ search right
-
Else (right half is sorted):
- If target lies in this range โ search right
- Else โ search left
๐ป Python Code
```python id="rs1"
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 is sorted
if nums[low] <= nums[mid]:
if nums[low] <= target < nums[mid]:
high = mid - 1
else:
low = mid + 1
# Right half is sorted
else:
if nums[mid] < target <= nums[high]:
low = mid + 1
else:
high = mid - 1
return -1
print(search([4, 5, 6, 7, 0, 1, 2], 0))
---
๐งพ Dry Run
For: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
* low = 0, high = 6 โ mid = 3 (7)
* Left half sorted โ target not in range โ go right
* low = 4, high = 6 โ mid = 5 (1)
* Right half sorted โ target in range โ go left
* low = 4, high = 4 โ mid = 4 (0)
๐ Found at index 4
---
โก Complexity
Time Complexity: O(log n)
Space Complexity: O(1)
---
๐ฅ Why This Works
* Uses binary search efficiently
* Leverages sorted half property
* Avoids full traversal
---
โ ๏ธ Edge Cases
* Single element array
* Target not present
* Pivot at start or end
---
๐ Conclusion
This problem teaches:
* Advanced binary search logic
* Handling rotated arrays
* Efficient searching in modified structures
Top comments (0)