Binary search is often the first algorithm we learn that feels like magic. It reduces a linear search of 1,000,000 items to just 20 comparisons. However, in technical interviews at top tech companies in India, you will rarely be asked to simply find a target in a sorted array. Instead, interviewers will test your ability to recognize monotonic properties and apply "binary search on the answer" to solve complex optimization problems. This article will guide you from the basic template to advanced applications.
When to use this pattern
Look for these signals in the problem statement:
- Sorted input: The array or matrix is explicitly sorted.
- O(log N) requirement: The problem asks for a time complexity better than O(N).
- Monotonicity: If a condition is valid for
X, it is also valid for allY > X(orY < X). - Optimization keywords: Phrases like "minimize the maximum", "maximize the minimum", or "find the smallest divisor".
The core idea
The essence of binary search is discarding half of the search space at every step. Instead of iterating one by one, we maintain a search space [left, right]. We check the mid point. Based on the result, we either find our answer, or we know definitively that the answer must lie in the left half or the right half.
When applying this to the answer (rather than an index), the search space is the range of possible answers (e.g., from 1 to the maximum possible value). We write a can_achieve(mid) helper function. If can_achieve(mid) is true, we might try to find an even better answer by searching the left or right half.
| Feature | Standard Binary Search | Binary Search on Answer |
|---|---|---|
| Search Space | Indices of a given sorted array [0, N-1] | Range of possible valid answers [min_val, max_val] |
| Target | A specific element in the array | The optimal value that satisfies a condition |
| Condition Check | arr[mid] == target | isValid(mid) helper function |
| Time Complexity | O(log N) | O(F * log(Max - Min)), where O(F) is the time for isValid |
Template
Here is the most robust binary search template. It uses left <= right and avoids integer overflow when calculating mid.
def binary_search(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 -1Worked examples
Example 1: Find First and Last Position of Element in Sorted Array
Problem: Given an array of integers sorted in non-decreasing order, find the starting and ending position of a given target value. If not found, return [-1, -1]. Must be O(log N).
Approach: Instead of finding the target and expanding outwards (which degrades to O(N) if the array is filled with the target), we run binary search twice.
- Find First: When
arr[mid] == target, we record the index but continue searching to the left (right = mid - 1) to see if there's an earlier occurrence. - Find Last: When
arr[mid] == target, we record the index but continue searching to the right (left = mid + 1).
def searchRange(nums, target):
def find_bound(is_first):
left, right = 0, len(nums) - 1
bound = -1
while left <= right:
mid = left + (right - left) // 2
if nums[mid] == target:
bound = mid
if is_first:
right = mid - 1
else:
left = mid + 1
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return bound
return [find_bound(True), find_bound(False)]Complexity: Time: O(log N) since we do two independent binary searches. Space: O(1).
Example 2: Koko Eating Bananas (Binary Search on Answer)
Problem: Koko loves to eat bananas. There are n piles of bananas, where the i-th pile has piles[i] bananas. The guards have gone and will come back in h hours. Koko can decide her bananas-per-hour eating speed of k. She wants to eat all the bananas before the guards return. Find the minimum integer k such that she can eat all the bananas within h hours.
Approach: This is a classic "minimize the maximum" problem.
- Search Space: The minimum speed
kis 1. The maximum speed is the size of the largest pile (since eating faster than the largest pile doesn't save any more time per pile). So,left = 1,right = max(piles). - Monotonicity: If Koko can finish the bananas at speed
k, she can definitely finish them at speedk + 1. We want the firstkthat works. - Helper Function:
can_finish(k)calculates the total hours needed at speedk. For each pile, hours needed isceil(pile / k). Iftotal_hours <= h, it returns true.
import math
def minEatingSpeed(piles, h):
def can_finish(k):
hours = 0
for p in piles:
hours += math.ceil(p / k)
return hours <= h
left, right = 1, max(piles)
ans = right
while left <= right:
mid = left + (right - left) // 2
if can_finish(mid):
ans = mid # Record valid speed
right = mid - 1 # Try to find a smaller speed
else:
left = mid + 1 # Speed too slow
return ansComplexity: Time: O(N log M) where N is the number of piles and M is the maximum pile size. Space: O(1).
Example 3: Allocate Minimum Number of Pages
Problem: You have N books, each with A[i] pages. You need to allocate these books to M students such that every student gets at least one book, and books are allocated contiguously. Find the allocation that minimizes the maximum number of pages assigned to a student.
Approach:
- Search Space: The minimum possible maximum pages is the largest single book (if a student gets just that book), so
left = max(A). The maximum possible is the sum of all books (if one student gets everything), soright = sum(A). - Monotonicity: If we can distribute books such that no student gets more than
Xpages, we can also do it forX + 1. We want the minimumX. - Helper Function:
is_possible(limit)greedily assigns books to a student until adding the next book exceedslimit. Then it assigns to the next student. If the number of students needed exceedsM, return false.
def findPages(A, M):
if len(A) < M:
return -1
def is_possible(limit):
students = 1
current_pages = 0
for pages in A:
if current_pages + pages > limit:
students += 1
current_pages = pages
if students > M:
return False
else:
current_pages += pages
return True
left = max(A)
right = sum(A)
ans = -1
while left <= right:
mid = left + (right - left) // 2
if is_possible(mid):
ans = mid
right = mid - 1
else:
left = mid + 1
return ansComplexity: Time: O(N log(Sum - Max)), where N is the number of books. Space: O(1).
Variations and pitfalls
1. The Infinite Loop Trap
If you use while (left < right) instead of while (left <= right), you must be extremely careful about how you update left and right. If you use left = mid and right = mid - 1, and left and right are adjacent, mid will equal left. Setting left = mid does nothing, causing an infinite loop.
Solution: Stick to the left <= right template with left = mid + 1 and right = mid - 1, and store the valid ans in a separate variable.
2. Floating Point Binary Search
Sometimes the answer isn't an integer. For example, finding the square root of a number to 5 decimal places.
In these cases, you don't use + 1 or - 1. You simply set left = mid or right = mid. The loop condition changes to a precision threshold: while (right - left > 1e-6).
3. Non-Monotonic Functions
Binary search only works if the search space is monotonic. If a condition is true for X, it must remain true for all Y > X (or Y < X). If the true/false values look like [False, True, False, True], binary search will fail. Always verify monotonicity before coding.
Practice checklist
To master this pattern, try solving these variations:
- Standard binary search in a 1D array.
- Binary search in a 2D matrix (treating it as a flattened 1D array).
- Finding the rotation pivot in a Rotated Sorted Array.
- "Minimize the maximum" problems (like Book Allocation or Split Array Largest Sum).
- "Maximize the minimum" problems (like Aggressive Cows).
Binary search on the answer is a frequent topic in rounds at companies like Amazon, Flipkart, and Swiggy. Once you train your eyes to spot the monotonic property, these hard problems become formulaic and straightforward.