Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 3

Binary Search on the Answer Space

This lesson is built with resources from youtube.com, reddit.com and 1 more site.

Introduction

Welcome to your third lesson in the "Advanced Algorithm Patterns" module. In our previous session, we mastered the two-pointer technique, learning how to efficiently solve problems on sorted arrays and linked lists. We saw how patterns like converging pointers and fast/slow pointers can drastically reduce time and space complexity.

Today, we shift our focus to another powerful optimization pattern: Binary Search on the Answer Space. Standard binary search finds an element in a sorted collection. This advanced variant, however, doesn't search through the input array. Instead, it searches for an optimal value within a range of possible answers.

This technique is the key to solving a common class of optimization problems, particularly those that ask you to "minimize a maximum value" or "maximize a minimum value" (e.g., find the minimum capacity needed, or the minimum time required). Your goal for this lesson is to learn how to identify these problems, define a search space over the potential answers, and implement a binary search to find the optimal solution efficiently.


From Sorted Arrays to Monotonic Conditions

You're already familiar with binary search on a sorted array. It works because if we check the middle element, we can definitively discard half of the array. The array's sorted nature provides a monotonic property: values consistently increase.

But what if the problem isn't about finding an element in a sorted array? What if it's about finding an optimal value that satisfies certain constraints? The key insight is that we don't need a sorted array; we just need a monotonic condition.

To understand this generalization, please watch the following video segment.

Data Structure and Algorithm Patterns for LeetCode Interviews – Tutorial

This segment from a freeCodeCamp.org tutorial explains the core idea of generalizing binary search from sorted arrays to any problem with a 'monotonic condition'. This is the theoretical foundation for what we're about to do.

Watch from 40:58 to 44:19. Focus on: The concept of a monotonic function that transitions from False to True just once. How binary search can be used to find the 'boundary'—the first True value. The generalized template that uses a condition(mid) check instead of a direct value comparison.

As the video explained, if we can define a function, let's call it is_feasible(k), that has this property:

  • If is_feasible(k) is True, then is_feasible(k+1) is also True.

This creates a virtual, boolean array like [False, False, ..., True, True, True]. Our goal is to find the index of the first True, which corresponds to the minimal value k that satisfies the condition.


The General Template

This leads us to a powerful, generalized template for solving this class of problems. The problem can usually be framed as:

Minimize k , such that condition(k) is True.

The following resource presents a robust template for this exact scenario.

Every type of Binary Search Pattern

This excellent Reddit post breaks down the 'Binary Search on the Answer Space' pattern into a simple, reusable template. We will be using this structure throughout the lesson.

Read the first section, titled 'Most Generalized Binary Search'. Pay close attention to the three key parts you need to define for any given problem: The search space boundaries (left and right). The design of the condition function. The final return value (left).

The three steps are always the same:

  1. Define the Search Space: Determine the absolute minimum and maximum possible values for your answer. These become your left and right boundaries.
  2. Design the condition function: This is the core of the problem. For a given guess mid from your search space, this function must determine if it's possible to satisfy the problem's constraints. This check is often implemented using a greedy approach.
  3. Run the Binary Search: Use the template to repeatedly shrink the search space until left and right converge on the minimal k that makes condition(k) true.

Pattern in Action: Minimize the Maximum

Let's see this pattern applied to some classic interview problems. The most common variant is "minimize the maximum," where you need to find the smallest possible value for some maximum limit (like capacity, sum, or time).

The next video provides an intuitive walkthrough of two such problems.

Coding Interview Patterns - Binary Search | 8 different problems in a single video

Nikhil Lohia's video provides a clear, step-by-step explanation of how to apply this pattern to two canonical problems. This will help you build intuition before we dive into the code.

Watch from 16:17 to 25:14. As you watch, try to map the explanation back to our three-step framework for each problem: What are the left and right boundaries of the answer space? How does the check (or feasible) function work greedily? How does the binary search narrow down the possibilities to find the minimum valid capacity/speed?

Let's solidify this with a deeper look at one of the problems from the video.

Example 1: Capacity to Ship Packages Within D Days (LeetCode 1011)

This problem asks for the least weight capacity of a ship to transport all packages within D days. This "least...capacity" is a strong signal for our pattern.

Let's apply our framework:

  1. Search Space:

    • left: The minimum possible capacity must be at least the weight of the single heaviest package. left = max(weights).
    • right: The maximum possible capacity would be to ship all packages in one day. right = sum(weights).
      Our answer lies somewhere in the range [max(weights), sum(weights)].
  2. condition(capacity) function:

    • Goal: Can we ship all packages in D days with a ship of the given capacity?
    • Logic (Greedy): Simulate the process. Iterate through the packages. Keep loading the current ship until the next package exceeds capacity. When it does, increment the day count and start loading a "new" ship with that package.
    • If the total days used are , return True. Otherwise, False.
  3. Binary Search:

    • We search within [left, right]. If condition(mid) is True, it means a capacity of mid is feasible. We might be able to do better (with a smaller capacity), so we record mid as a potential answer and try the lower half: right = mid. If condition(mid) is False, mid is too small, and we must increase our capacity: left = mid + 1.

The Reddit post Every type of Binary Search Pattern you read earlier walks through this exact logic in its "Advanced Application" section for problem 1011.

Koko Eating Bananas: Binary Search for Optimal Speed
This image summarizes the logic for 'Koko Eating Bananas', another classic problem solved with this pattern. The problem asks for the minimum eating speed 'k' to finish all bananas in 'h' hours. The search space for 'k' is binary searched, and a feasibility function checks if a given speed 'k' is sufficient.

A Hard Problem Deep Dive: Split Array Largest Sum (LeetCode 410)

For a Staff-level interview, you're expected to recognize underlying patterns even in problems that appear more complex. "Split Array Largest Sum" is a LeetCode Hard problem, but it is structurally identical to "Capacity to Ship Packages."

Problem: Given an array nums and an integer k, split nums into k subarrays to minimize the largest sum of any subarray.

Let's map this to our pattern:

  • "Capacity" becomes "Largest Sum".
  • "D days" becomes "k subarrays".

The logic is the same: we binary search for the answer, which is the "minimized largest sum."

Split Array Largest Sum Solution

This resource provides a detailed explanation of the solution in text and, importantly, a Go implementation.

Read 'Solution 1: Binary Search' and review the 'Go' implementation. Notice how the check function is nearly identical to the logic for the ship capacity problem. The Go code uses sort.Search, which is the idiomatic way to implement this binary search pattern in Go. It abstracts away the while left < right loop.

Justifying Correctness (Staff+ Depth)

A good candidate gives the right answer. A great candidate can explain why it's right. A common question about this pattern is: "Your binary search finds the minimal value x that makes check(x) true. But how do you know x is an achievable sum? The search space contains many values that can't be formed by any split."

The resource Every type of Binary Search Pattern provides an elegant proof by contradiction for this in its analysis of problem 410. The argument is:

  1. Let k be the minimal value for which feasible(k) is True.
  2. Assume, for the sake of contradiction, that no split actually produces a largest-sum of k. This means every possible split results in a largest-sum that is less than k.
  3. If this is true, it implies that the greedy check for feasible(k-1) would also pass (since the sums never actually reach k, they certainly won't exceed k-1).
  4. This means feasible(k-1) would be True.
  5. This contradicts our initial statement that k is the minimal value for which the condition is true.
  6. Therefore, our assumption must be false, and a split that results in a largest sum of exactly k must exist.

Understanding and being able to articulate this logic demonstrates a deep command of the algorithm beyond rote memorization.


Conclusion

Today, we've added a powerful and non-obvious technique to your algorithmic toolkit. Binary search isn't just for finding elements in sorted arrays; it's a general-purpose strategy for zeroing in on an optimal value in any problem with a monotonic search space.

Key Takeaways:

  • Pattern Recognition: Look for problems asking to "minimize the maximum" or "maximize the minimum." These are strong indicators for binary searching on the answer.
  • Framework: The solution pattern involves three steps:
    1. Define the left and right boundaries of the answer space.
    2. Implement a check(k) or feasible(k) function that greedily verifies if a given value k is a valid solution.
    3. Use a binary search template to find the first k for which check(k) is true.
  • Go Idiom: In Go, sort.Search is the preferred tool for implementing this pattern. It's concise and less prone to off-by-one errors.
  • Staff-Level Depth: Be prepared to justify why the algorithm works. The proof by contradiction for problems like "Split Array Largest Sum" is an excellent example of the depth expected.

In our next lesson, we will explore monotonic stacks and queues. This is another specialized pattern that allows you to solve a different class of problems, like "next greater element," in optimal linear time.