Theory
You can use binary search if all these conditions are satisfied 1. Monotonic PropertyThere must be a monotonic relationship in the search space:
- If some property/condition is true for X, it is also true for all values > X (or all values < X).
- In other words, the answer space is sorted with respect to the property you’re checking.
- If we’re still in the “before” region → search right
- If we’ve found the transition → search left
- This eliminates half the search space
- We always move toward the single element
- The loop condition left < right ensures convergence
- We find the exact position of the single element
Patterns
Binary Search Loop Patterns:Overview The choice betweenleft <= rightvsleft < right
while left <= right: and while left < right: in binary search depends on the specific problem and
what you’re trying to find. Here are the common patterns:
Pattern 1: while left <= right: (Inclusive Search)
When to Use:
- Finding exact target in a sorted array
- Finding first/last occurrence of a target
- Finding floor/ceil values
- Problems where you need to check the final element
- Loop continues until
left > right(no elements left to check) - Both
leftandrightare inclusive bounds - You typically return
-1or a sentinel value if target not found - The final state is
left = right + 1
Pattern 2: while left < right: (Exclusive Search)
When to Use:
- Finding minimum/maximum in a range
- Binary search on answer space (optimization problems)
- Problems where you’re guaranteed to find an answer
- When you want to converge to a single element
- Loop continues until
left == right(converges to single element) - The final state is
left == right == answer - You typically return
leftorright(they’re equal) - No need for sentinel values
Key Differences Summary
| Aspect | left <= right | left < right |
|---|---|---|
| Loop Condition | while left <= right: | while left < right: |
| Final State | left = right + 1 | left = right |
| Return Value | Usually -1 or sentinel | Usually left or right |
| Use Case | Finding exact targets | Finding min/max/optimization |
| Guarantee | May not find target | Always converges to answer |
| Bounds | Inclusive | Converging |
Decision Framework
Useleft <= right when:
- You’re searching for an exact target that may not exist
- You need to find first/last occurrence of a value
- You’re looking for floor/ceil values
- You need to check all possible positions
left < right when:
- You’re finding the minimum/maximum in a range
- You’re doing binary search on answer space
- You’re guaranteed to find an answer
- You want to converge to a single element
Common Mistakes
- Using
left < rightfor exact target search: May miss the target if it’s at the boundary - Using
left <= rightfor optimization problems: May cause infinite loops or incorrect convergence - Incorrect return values: Returning wrong variable in final state
- Wrong mid calculation: Can cause overflow or incorrect convergence
Tips for Implementation
- Always consider the final state of your variables
- Think about what you’re returning and when the loop terminates
- Test edge cases to ensure your loop condition is correct
- Use inclusive search when you need to check every possible position
- Use exclusive search when you’re converging to a guaranteed answer
Problems
Solution to All Linked List solutions Github
Easy Problems
-
Binary Search to find X in sorted array
- Find an element X in a sorted array using binary search
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Implement Lower Bound
- Find the index of the first element that is greater than or equal to X
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Implement Upper Bound
- Find the index of the first element that is greater than X
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Search Insert Position
- Find the index where X should be inserted to maintain sorted order
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Floor/Ceil in Sorted Array
- Find floor and ceil of X in a sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Find First and Last Position of Element in Sorted Array
- Find the first and last occurrence of X in a sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Count Occurrences in Sorted Array
- Count the number of occurrences of X in a sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
Binary Search on an Unstored Array
1. There’s a monotonic (ordered) property, not necessarily sorted values
You need a binary-searchable condition or monotonic predicate. That is: If a predicate P(i) is False for some index i, then it is also False for all j < i (or j > i) — and vice versa. This allows you to “eliminate” half the array on each step. 🔹 Example: Peak Element Problem Array is unsorted, but: Ifarr[mid] < arr[mid + 1], you can move right — because there’s a guaranteed peak in that direction.
You don’t need sorted values — just a guarantee of direction.
2. Finding Rotation Point in Rotated Sorted Array
Even though the array is not sorted end-to-end, you can binary search for the minimum element (i.e., the rotation point) because:- One half is always sorted.
- The other half contains the inflection.
So you use the condition
arr[mid] > arr[right]to decide which half to discard.
3. Search in Bitonic Array (increasing then decreasing)
You can use binary search to:- First find the maximum element (peak),
- Then binary search separately in the increasing and decreasing parts.
- Each half is sorted (one increasing, one decreasing).
- You have a structure to exploit.
4. First/Last Position That Satisfies a Condition
Even in unsorted input, if you’re searching along a time axis, distance, or function input, you can binary search the input domain rather than the array directly. 🔹 Example: Minimize the maximum load (Scheduling problem) Given N jobs and K workers, what’s the minimum possible maximum load?- The array is job durations (unsorted), but:
- The predicate “Can you assign with max load X?” is monotonic → if you can assign with load X, you can with X + 1.
-
Search in Rotated Sorted Array
- Find X in a rotated sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Search in Rotated Sorted Array II
- Find X in a rotated sorted array with duplicates
- Time Complexity: O(log n) average, O(n) worst case
- Space Complexity: O(1)
-
Find Minimum in Rotated Sorted Array
- Find the minimum element in a rotated sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Find out how many times the array has been rotated
- Find the number of times a sorted array has been rotated
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Single Element in a Sorted Array
- Find the single element in a sorted array where all elements appear twice except one
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Peak Index in a Mountain Array
- Find the peak index in a mountain array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Find Peak Element
- Find any peak element in an array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Square Root of a Number
- Find the square root of a number using binary search
- Time Complexity: O(log n)
- Space Complexity: O(1)
Medium Problems
-
Nth Root of a Number
- Find the nth root of a number using binary search
- Time Complexity: O(n * log(m * 10^d)) where d is the number of decimal places
- Space Complexity: O(1)
-
Koko Eating Bananas
- Find the minimum eating speed to eat all bananas within h hours
- Time Complexity: O(n * log(max(piles)))
- Space Complexity: O(1)
-
Minimum Days to Make M Bouquets
- Find the minimum days to make m bouquets
- Time Complexity: O(n * log(max(bloomDay)))
- Space Complexity: O(1)
-
Find the Smallest Divisor Given a Threshold
- Find the smallest divisor such that the sum of division results is less than or equal to threshold
- Time Complexity: O(n * log(max(nums)))
- Space Complexity: O(1)
-
Capacity to Ship Packages Within D Days
- Find the minimum capacity to ship all packages within d days
- Time Complexity: O(n * log(sum(weights) - max(weights)))
- Space Complexity: O(1)
-
Kth Missing Positive Number
- Find the kth missing positive number in a sorted array
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Aggressive Cows
- Find the maximum minimum distance between cows
- Time Complexity: O(n * log(max(stalls) - min(stalls)))
- Space Complexity: O(1)
-
Book Allocation Problem
- Allocate books to students such that the maximum pages assigned to a student is minimum
- Time Complexity: O(n * log(sum(pages) - max(pages)))
- Space Complexity: O(1)
-
Split Array Largest Sum
- Split array into k subarrays such that the largest sum is minimum
- Time Complexity: O(n * log(sum(nums) - max(nums)))
- Space Complexity: O(1)
-
Painter’s Partition Problem
- Allocate boards to painters such that the time taken is minimum
- Time Complexity: O(n * log(sum(lengths) - max(lengths)))
- Space Complexity: O(1)
-
Minimize Max Distance to Gas Station
- Find the minimum value of dist.
- Time Complexity: O(n * log(max_distance / precision))
- Space Complexity: O(1)
Hard Problems
-
Median of Two Sorted Arrays
- Find the median of two sorted arrays
- Time Complexity: O(log(min(n, m)))
- Space Complexity: O(1)
-
K-th Element of Two Sorted Arrays
- Find the k-th element of two sorted arrays
- Time Complexity: O(log(min(n, m)))
- Space Complexity: O(1)
Matrix Problems
-
Search in a 2D Matrix
- Search for a target in a row-wise and column-wise sorted matrix
- Time Complexity: O(log(m * n))
- Space Complexity: O(1)
-
Search in a 2D Matrix II
- Search for a target in a row-wise and column-wise sorted matrix
- Time Complexity: O(m + n)
- Space Complexity: O(1)
-
Find Single Element in Sorted Array
- Find the single element in a sorted array where all elements appear twice except one
- Time Complexity: O(log n)
- Space Complexity: O(1)
-
Find Peak Element II
- Find a peak element in a 2D matrix
- Time Complexity: O(n * log(m))
- Space Complexity: O(1)
-
Matrix Median
- Find the median of a row-wise sorted matrix
- Time Complexity: O(32 * r * log(c))
- Space Complexity: O(1)