Shrinking the Search Space with Binary Search

Nov 3, 2024· 7 min read
Shrinking the Search Space with Binary Search
type
status
date
summary
tags
category
icon
password
featured
freq
difficulty
Binary Search is one of the most efficient algorithms for locating an element or index within a sorted array, list, or structure. Unlike Linear Search, which examines each element sequentially, Binary Search exploits the sorted order to cut the search space in half at every step. This divide-and-conquer strategy ensures that the algorithm runs in O(log n) time, a dramatic improvement over the O(n) complexity of linear scanning.
While Binary Search is traditionally taught in the context of sorted arrays, its power extends further. The key insight is that Binary Search can be applied whenever the search space exhibits a monotonic property—that is, a condition that transitions only once from false → true (or vice versa).
For example:
  • Answer space problems, where you’re searching for the smallest or largest value that satisfies a condition (e.g., minimum capacity, maximum feasible time).
  • Optimization problems, where the function being evaluated is monotonic across the domain.
In these cases, Binary Search doesn’t just find values—it becomes a general search framework for problems like searching for the boundary or point of transition.
 

Core Idea

At its heart, Binary Search is fundamentally a divide-and-conquer algorithm:
  1. Start with the entire search space.
  1. Check the middle element (or midpoint condition).
  1. Decide whether to continue searching in the left half or the right half.
  1. Repeat until the search space collapses to the answer or becomes empty.
This recursive halving guarantees logarithmic performance, making Binary Search a cornerstone of efficient algorithm design.
 

Common Usages of Binary Search

Binary Search appears in many algorithmic patterns and real-world systems. Below are the most common use cases.

1. Value Lookup and Existence Check

This is the classic template for checking if a target exists and returning its index.
It uses a closed interval [left, right] and narrows the space until the pointers meet.
 

2. Boundary and Insertion Point Searches

These templates are used to find the correct insertion index for an element, even if the element doesn't exist. They use a half-open interval approach (left < right) where the result is always left.
Pattern Name
Goal
Condition to Advance left
Result after loop
Lower Bound
Find the first occurrence of ≥ target (Smallest index greater than or equal to target).
sorted_list[mid] < target
left is the insertion index.
Upper Bound
Find the position after the last occurrence of <= target (Smallest index strictly greater than target).
sorted_list[mid] <= target
left is the index after the target's group.
Template —Lower Bound
Template —Upper Bound
 

3. Finding the Closest Element

To find the closest element to a target value, combine a lower bound search with a small post-processing step comparing neighbors.
Use Case: Nearest temperature, closest stock price, or minimizing |nums[i] − target|.
 

4. Binary Search on the Answer

This is a meta-technique where you binary search not over indices, but over possible answers.
This pattern appears in scheduling, optimization, and many “minimize the maximum” problems.
Template — Minimize Feasible Value
 
Example: Koko Eating Bananas (LeetCode 875)
Find the minimum eating speed k so Koko can finish all piles within h hours.
Monotonic property: If Koko can finish with speed = k, she can also finish with any speed > k.
 

Common Pitfalls

  1. Infinite loops:
    1. Always ensure the range shrinks (left < rightleft = mid + 1 or right = mid).
  1. Off-by-one errors:
    1. Closed vs. half-open intervals produce different exit conditions.
  1. Integer overflow (in lower-level languages):
    1. Use mid = left + (right - left)//2 instead of (left + right)//2 to avoid integer overflow.
 

Binary Search Variants in the Wild

Binary search is not just simple number lookups — it’s a pattern that adapts to many complex problem types once you recognize the underlying monotonic behavior.
Once you see that your “search condition” behaves monotonically, even if the data looks nonlinear or multidimensional, you can usually model it as a binary search on some ordered feature — index, value, or even decision space.
Problem
Binary Search Target
Example
Rotated Sorted Array
Search in rotated array using pivot logic
LeetCode 33
Peak Element
Find local maximum using slope property
LeetCode 162
Minimum in Rotated Array
Find min value via monotonic segments
LeetCode 153
Allocate Books / Split Array
Minimize largest partition sum
LeetCode 410
Matrix Search
Binary search over 2D matrix or flattened index
LeetCode 74
Search in a Sorted Array of Unknown Size
Determine search bounds first (exponential expansion), then apply binary search within them
LeetCode 702

Final Thought

By repeatedly dividing the search space in half and narrowing down where the target might be, binary search achieves a time complexity of O(log⁡n), making it vastly faster than linear search for large datasets. Its efficiency, simplicity, and predictability make it a critical building block in many algorithms and real-world applications.
 
上一篇
对话系统:从人机交流走向理解与互动
下一篇
Solving Problems with the Two-Pointers Technique