Skip to main content
Binary Search Pattern Binary Search is a divide-and-conquer algorithm that repeatedly halves the search space. It reduces O(n) linear search to O(log n) by eliminating half the possibilities at each step.
Quick Recognition: If you see “sorted array” or need to minimize/maximize something with a feasibility check, Binary Search is likely the answer!

Pattern Recognition Checklist

Use Binary Search When

  • Array is sorted (or has monotonic property)
  • Need O(log n) instead of O(n)
  • Minimize/maximize with feasibility check
  • Finding transition point where condition changes
  • Search space can be halved each step

Don't Use When

  • Array is unsorted with no order
  • Need to find all occurrences
  • Linear scan is already O(n) and sufficient
  • No clear way to eliminate half

When to Use

Sorted Arrays

Finding elements, insertion points, or bounds

Monotonic Functions

Finding transition points where condition changes

Optimization Problems

Minimizing/maximizing values with feasibility check

Hidden Sorted Space

Rotated arrays, peak finding, matrix search

Pattern Variations

Find exact target in sorted array.
def binary_search(arr, target):
    """Find target in sorted array, return index or -1"""
    left, right = 0, len(arr) - 1
    
    while left <= right:
        mid = left + (right - left) // 2  # Avoid overflow
        
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    
    return -1

2. Lower Bound (First Occurrence)

Find first element greater than or equal to target.
def lower_bound(arr, target):
    """Find first index where arr[i] >= target"""
    left, right = 0, len(arr)
    
    while left < right:
        mid = left + (right - left) // 2
        
        if arr[mid] < target:
            left = mid + 1
        else:
            right = mid  # Don't exclude mid, it could be answer
    
    return left

3. Upper Bound (Last Occurrence)

Find first element greater than target.
def upper_bound(arr, target):
    """Find first index where arr[i] > target"""
    left, right = 0, len(arr)
    
    while left < right:
        mid = left + (right - left) // 2
        
        if arr[mid] <= target:
            left = mid + 1
        else:
            right = mid
    
    return left

4. Binary Search on Answer

When searching for optimal value, not index.
def min_capacity_to_ship(weights, days):
    """Minimum ship capacity to ship all packages in given days"""
    
    def can_ship(capacity):
        current_weight = 0
        days_needed = 1
        
        for weight in weights:
            if current_weight + weight > capacity:
                days_needed += 1
                current_weight = 0
            current_weight += weight
        
        return days_needed <= days
    
    # Search space: [max single weight, sum of all weights]
    left = max(weights)
    right = sum(weights)
    
    while left < right:
        mid = left + (right - left) // 2
        
        if can_ship(mid):
            right = mid  # Try smaller capacity
        else:
            left = mid + 1  # Need more capacity
    
    return left

Classic Problems

Problem: Search for target in rotated sorted array.Approach: Find which half is sorted, determine if target is in that half.Time: O(log n) | Space: O(1)
Problem: Find any peak element (greater than neighbors).Approach: Compare mid with mid+1, move towards the larger side.Time: O(log n) | Space: O(1)
Problem: Search in row-wise and column-wise sorted matrix.Approach: Treat as 1D array or start from top-right corner.Time: O(log(m*n)) or O(m+n) | Space: O(1)
Problem: Minimum eating speed to finish all bananas in h hours.Approach: Binary search on answer with feasibility check.Time: O(n log m) | Space: O(1)
Problem: Find median of two sorted arrays in O(log(m+n)).Approach: Binary search on partition point of smaller array.Time: O(log(min(m,n))) | Space: O(1)

Search in Rotated Sorted Array

def search_rotated(nums, target):
    """Search for target in rotated sorted array"""
    left, right = 0, len(nums) - 1
    
    while left <= right:
        mid = (left + right) // 2
        
        if nums[mid] == target:
            return mid
        
        # Left half is sorted
        if nums[left] <= nums[mid]:
            if nums[left] <= target < nums[mid]:
                right = mid - 1
            else:
                left = mid + 1
        # Right half is sorted
        else:
            if nums[mid] < target <= nums[right]:
                left = mid + 1
            else:
                right = mid - 1
    
    return -1

Template Code

# Template 1: Standard (find exact match)
def binary_search_standard(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + (right - left) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

# Template 2: Lower bound (first >= target)
def binary_search_lower(arr, target):
    left, right = 0, len(arr)
    while left < right:
        mid = left + (right - left) // 2
        if arr[mid] < target:
            left = mid + 1
        else:
            right = mid
    return left

# Template 3: Binary search on answer
def binary_search_answer(low, high, is_valid):
    while low < high:
        mid = low + (high - low) // 2
        if is_valid(mid):
            high = mid
        else:
            low = mid + 1
    return low

Common Mistakes

Avoid These Pitfalls:
  1. Integer Overflow: Use mid = left + (right - left) / 2 instead of (left + right) / 2
  2. Infinite Loop: Ensure left or right changes every iteration
  3. Off-by-one: Know when to use left <= right vs left < right
  4. Wrong boundary: Include or exclude mid based on problem type

Debugging Checklist

When your Binary Search solution fails:
1

Check Initial Bounds

Is left = 0 and right = len - 1 or right = len?
2

Check Loop Condition

Use left <= right for exact match, left < right for bounds.
3

Check Mid Calculation

Use left + (right - left) / 2 to avoid overflow.
4

Check Movement

Is mid included or excluded? (right = mid vs right = mid - 1)
5

Check Return Value

What should be returned when element is not found?

The Three Templates

Understanding which template to use is crucial:
TemplateLoop ConditionUse CaseAfter Loop
Standardleft <= rightFind exact matchReturn -1 if not found
Lower Boundleft < rightFirst >= targetleft is answer
Upper Boundleft < rightFirst > targetleft is answer

Complexity Quick Reference

Problem TypeTimeSpaceKey Insight
Standard searchO(log n)O(1)Exact match
Lower/Upper boundO(log n)O(1)First occurrence
Search on answerO(n log range)O(1)Feasibility check
Rotated arrayO(log n)O(1)Find sorted half
Peak findingO(log n)O(1)Compare with neighbor

Interview Problems by Company

ProblemCompanyKey Concept
Binary SearchAllBasic template
Search Insert PositionAmazon, GoogleLower bound
First Bad VersionMeta, MicrosoftBoolean search
Sqrt(x)AmazonSearch on answer
Valid Perfect SquareGoogleSearch on answer

Interview Tips

Script for interviews:
  1. “Since the array is sorted, I can use Binary Search for O(log n) time.”
  2. “I’ll maintain two pointers, left and right, representing the search space.”
  3. “At each step, I calculate mid and compare with target.”
  4. “Based on comparison, I eliminate half the search space.”
  5. “I repeat until I find the target or the space is exhausted.”
Interviewer SaysYou Should Think
”Array is sorted”Binary Search!
”Can you do better than O(n)?”Binary Search might work
”Find minimum/maximum that satisfies…”Binary Search on answer
”Array is rotated”Modified Binary Search
”Find first/last occurrence”Lower/Upper bound
Be ready for these follow-ups:
  • “What if there are duplicates?” → Use lower/upper bound
  • “What if array is rotated?” → Find sorted half first
  • “Can you do it without extra space?” → Binary Search is already O(1) space
  • “What about very large arrays?” → Binary Search scales well

Practice Problems

ProblemDifficultyLink
Binary SearchEasyLeetCode 704
Search Insert PositionEasyLeetCode 35
Search in Rotated Sorted ArrayMediumLeetCode 33
Find Peak ElementMediumLeetCode 162
Median of Two Sorted ArraysHardLeetCode 4

Practice Roadmap

1

Day 1: Standard Search

  • Solve: Binary Search, Search Insert Position
  • Focus: Master the basic template perfectly
2

Day 2: Bounds

  • Solve: Find First and Last Position, First Bad Version
  • Focus: Lower bound vs upper bound
3

Day 3: Modified Arrays

  • Solve: Search in Rotated Array, Find Peak Element
  • Focus: Finding the sorted half
4

Day 4: Search on Answer

  • Solve: Koko Eating Bananas, Capacity To Ship
  • Focus: Binary search on the result space
Interview Tip: When you see “sorted array” or “minimize/maximize” with a feasibility check, think Binary Search immediately.