All Patterns
🔍
mediumPattern #04
Binary Search
Halve the search space every step on any monotonic condition.
What is this pattern?
Binary search is not just for finding a value in a sorted array. Any time the answer space has a monotonic property (feasible vs not feasible), you can binary search on the answer itself — turning O(n) linear scans into O(log n).
When to use it
- Array is sorted or partially sorted
- Finding a boundary (first/last occurrence)
- Answer is a number and feasibility is monotonic ("can I do it in X days?")
- Looking for a peak, minimum in rotated, or kth element
Key Insight
Always define: what does mid represent, and which half can I eliminate? The three templates — find exact, find leftmost, find rightmost — cover all cases. Get the loop invariant right and the off-by-one errors disappear.
Pro Content
The Java template and practice problems for this pattern are part of the Pro plan. Upgrade to unlock all patterns, 500+ problems, and Aria code reviews.
From ₹3,999 for a year · one-time, no auto-renewal