Binary search, including binary search on the answer

Master the binary search pattern and learn how to apply \"binary search on the answer\" to solve complex optimization problems in coding interviews.

intermediate14 min readBy CureBugs EditorialUpdated 5 Nov 2026

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:

  1. Sorted input: The array or matrix is explicitly sorted.
  2. O(log N) requirement: The problem asks for a time complexity better than O(N).
  3. Monotonicity: If a condition is valid for X, it is also valid for all Y > X (or Y < X).
  4. 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.

FeatureStandard Binary SearchBinary Search on Answer
Search SpaceIndices of a given sorted array [0, N-1]Range of possible valid answers [min_val, max_val]
TargetA specific element in the arrayThe optimal value that satisfies a condition
Condition Checkarr[mid] == targetisValid(mid) helper function
Time ComplexityO(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 -1

Worked 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.

  1. 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.
  2. 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.

  1. Search Space: The minimum speed k is 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).
  2. Monotonicity: If Koko can finish the bananas at speed k, she can definitely finish them at speed k + 1. We want the first k that works.
  3. Helper Function: can_finish(k) calculates the total hours needed at speed k. For each pile, hours needed is ceil(pile / k). If total_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 ans

Complexity: 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:

  1. 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), so right = sum(A).
  2. Monotonicity: If we can distribute books such that no student gets more than X pages, we can also do it for X + 1. We want the minimum X.
  3. Helper Function: is_possible(limit) greedily assigns books to a student until adding the next book exceeds limit. Then it assigns to the next student. If the number of students needed exceeds M, 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 ans

Complexity: 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.

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.

Mock interview

Solve one like this with an interviewer watching

Getting the answer alone is half the round. The other half is clarifying the problem, explaining your approach, coding while you talk and handling the follow-up. Try it on a problem you haven't seen.

  • A timed problem in a real editor, judged on hidden tests
  • Hints if you ask, and they count against you like they would in the room
  • A scored report that quotes your answers and says what to fix
Start a mock coding round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
DSA patterns•intermediate

The two pointers pattern

15 min read
DSA patterns•intermediate

The sliding window pattern

11 min read
DSA patterns•intermediate

Prefix sums and hashing

11 min read
DSA patterns•intermediate

The monotonic stack pattern

12 min read
Binary search, including binary search on the answer · CureBugs