| name | Modified Binary Search | |||
|---|---|---|---|---|
| slug | modified-binary-search | |||
| category | searching | |||
| difficulty | intermediate | |||
| timeComplexity | O(log n) | |||
| spaceComplexity | O(1) | |||
| recognitionTips |
|
|||
| commonVariations |
|
|||
| relatedPatterns | ||||
| keywords |
|
|||
| estimatedTime | 3-4 hours |
Modified Binary Search extends classic binary search to handle complex scenarios. The key insight is that binary search works whenever you can eliminate half the search space based on a condition.
- Sorted or partially sorted array
- Need O(log n) time
- Can determine which half to eliminate
- Finding boundaries, peaks, or special elements
- Define left and right boundaries
- Calculate midpoint
- Make decision based on mid element
- Eliminate half search space
- Repeat until found
function search(array, target):
left = 0, right = len - 1
while left <= right:
mid = left + (right - left) / 2
if found: return mid
elif go_left: right = mid - 1
else: left = mid + 1
return -1
Binary search on sorted array [1, 3, 5, 7, 9], target = 5:
- mid = 2 (value 5) → found!
Problem: Integer overflow with (left + right) / 2 Solution: Use left + (right - left) / 2
Problem: Infinite loops from wrong boundary updates Solution: Ensure left/right always converge
- Check for ordered property (not just sorted)
- Handle empty array, single element edge cases
- Be careful with
<=vs<in while condition - Test with even and odd length arrays
Algorithms below are auto-populated from repository.
No closely related patterns yet.