allizwell.jobsdoor360.in

Binary Search on Answer

Data Structures and Algorithms / Searching and Sorting / Binary Search on Answer

Binary Search on Answer in Data Structures and Algorithms

Binary Search on Answer is an optimization technique that uses Binary Search to find the smallest or largest value satisfying a particular condition. Instead of searching for an element in a sorted array, we search through a range of possible answers. It is commonly used in problems involving minimum capacity, maximum distance, minimum time, and resource allocation.

1. What is Binary Search on Answer?

In ordinary Binary Search, we search for a target element in a sorted collection. In Binary Search on Answer, we search for an optimal numerical answer within a range.

We define a condition that tells us whether a particular answer is possible or valid. Then we use Binary Search to find the required answer efficiently.

For example, suppose we want to find the minimum capacity required to transport all packages within a given number of days. We can test different capacities and determine whether each capacity is sufficient.

Simple Example

Suppose a machine can process a certain number of items per hour. We want to find the minimum processing speed needed to finish all items within a fixed time limit.

  • A very low speed may not finish the work on time.
  • A higher speed may finish the work within the time limit.
  • Once a speed is sufficient, every higher speed is also sufficient.

We can use Binary Search to find the smallest sufficient speed instead of checking every possible speed.

2. Why Do We Use Binary Search on Answer?

Some optimization problems have a large number of possible answers. Checking every possible answer one by one may require too much time.

Binary Search on Answer reduces the search range by half after every step, making the solution much more efficient.

Example: Finding Minimum Capacity

Imagine that we have packages with different weights and must transport them within a fixed number of days.

We need to find the minimum ship capacity that allows all packages to be transported within the given days.

  • A capacity that is too small is not valid.
  • A sufficient capacity is valid.
  • Any capacity larger than a valid capacity is also valid.

This creates a monotonic condition, which makes Binary Search applicable.

3. Understanding Monotonicity

Monotonicity is the most important concept in Binary Search on Answer.

A condition is monotonic when its results change in only one direction as the candidate answer increases or decreases.

Type 1: False to True

In this pattern, smaller values are invalid and larger values become valid.

Answer:    1  2  3  4  5  6  7  8
Condition: F  F  F  T  T  T  T  T

We want to find the first valid answer, which is 4.

Type 2: True to False

In this pattern, smaller values are valid and larger values eventually become invalid.

Answer:    1  2  3  4  5  6  7  8
Condition: T  T  T  T  F  F  F  F

We want to find the last valid answer, which is 4.

Important: Binary Search on Answer works when the feasibility condition has a monotonic structure. If valid and invalid answers are mixed without a clear transition, ordinary Binary Search cannot be applied directly.

4. General Approach

The general process for solving Binary Search on Answer problems is:

  1. Understand what value needs to be minimized or maximized.
  2. Determine the minimum and maximum possible answers.
  3. Create a function that checks whether a candidate answer is valid.
  4. Check whether the valid and invalid answers follow a monotonic pattern.
  5. Apply Binary Search to the answer range.
  6. Return the smallest or largest valid answer according to the problem.

5. Finding the First Valid Answer

When smaller answers are invalid and larger answers are valid, we need to find the first answer for which the condition becomes true.

This is often called the first true pattern.

Algorithm

low = minimum possible answer
high = maximum possible answer

while low < high:

    mid = low + (high - low) / 2

    if isPossible(mid):
        high = mid

    else:
        low = mid + 1

return low

Explanation:

  • If mid is valid, the answer may be mid or smaller, so move high to mid.
  • If mid is invalid, all smaller answers are also invalid, so move low to mid + 1.
  • When low equals high, the first valid answer has been found.

6. Finding the Last Valid Answer

Sometimes smaller answers are valid and larger answers are invalid. In this case, we need to find the last valid answer.

Algorithm

low = minimum possible answer
high = maximum possible answer

while low < high:

    mid = low + (high - low + 1) / 2

    if isPossible(mid):
        low = mid

    else:
        high = mid - 1

return low

Explanation:

  • If mid is valid, we try to find a larger valid answer by moving low to mid.
  • If mid is invalid, all larger answers are also invalid, so move high to mid - 1.
  • When low equals high, the last valid answer has been found.
The upper-middle calculation in the second approach is important. It prevents an infinite loop when low and high differ by one.

7. Example Problem: Minimum Ship Capacity

Suppose a shipping company must transport packages within a fixed number of days. Each package has a specific weight, and packages must be shipped in their given order.

The ship can carry packages up to a maximum weight on each day. We need to find the minimum ship capacity that allows all packages to be delivered within the required number of days.

Problem Example

Package weights:

weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Required delivery time:

days = 5

Find the minimum ship capacity required to transport all packages within 5 days.

8. Finding the Search Range

Before applying Binary Search, we must determine the minimum and maximum possible capacities.

Minimum Possible Capacity

The ship must be able to carry the heaviest individual package. Therefore, the minimum possible capacity is the maximum package weight.

low = maximum package weight

Maximum Possible Capacity

The ship could carry all packages on a single day if its capacity equals the sum of all package weights. Therefore, the maximum possible capacity is the total weight of all packages.

high = sum of all package weights

For our example:

weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Minimum capacity = 10
Maximum capacity = 55

Search Range: [10, 55]

9. Creating the Feasibility Function

The feasibility function checks whether a given ship capacity can transport all packages within the required number of days.

We process packages in their original order. If adding the next package would exceed the capacity, we start a new day and load that package on the new day.

C++ Feasibility Function

bool isPossible(vector<int>& weights,
                int days,
                long long capacity) {

    int requiredDays = 1;

    long long currentLoad = 0;

    for (int weight : weights) {

        if (currentLoad + weight > capacity) {

            requiredDays++;

            currentLoad = weight;
        }
        else {

            currentLoad += weight;
        }
    }

    return requiredDays <= days;
}

Explanation:

  • Start with the first day.
  • Add packages while the total weight does not exceed capacity.
  • If the next package exceeds capacity, start another day.
  • Count how many days are required.
  • If the required days are less than or equal to the allowed days, the capacity is valid.

10. Complete C++ Implementation

Now let us combine the feasibility function with Binary Search to find the minimum required ship capacity.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool isPossible(vector<int>& weights,
                int days,
                long long capacity) {

    int requiredDays = 1;

    long long currentLoad = 0;

    for (int weight : weights) {

        if (currentLoad + weight > capacity) {

            requiredDays++;

            currentLoad = weight;
        }
        else {

            currentLoad += weight;
        }
    }

    return requiredDays <= days;
}

long long minimumCapacity(vector<int>& weights,
                          int days) {

    long long low = *max_element(
        weights.begin(), weights.end()
    );

    long long high = 0;

    for (int weight : weights) {
        high += weight;
    }

    while (low < high) {

        long long mid = low + (high - low) / 2;

        if (isPossible(weights, days, mid)) {

            high = mid;
        }
        else {

            low = mid + 1;
        }
    }

    return low;
}

int main() {

    vector<int> weights = {
        1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    };

    int days = 5;

    cout << "Minimum ship capacity: "
         << minimumCapacity(weights, days);

    return 0;
}

Output

Minimum ship capacity: 15

11. Dry Run of Binary Search on Answer

Let us understand how the algorithm finds the minimum ship capacity.

Input:

weights = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
days = 5

low = 10
high = 55

We repeatedly calculate mid and check whether the packages can be delivered within 5 days.

Step Low High Mid Possible? Action
1 10 55 32 Yes Search smaller capacity
2 10 32 21 Yes Search smaller capacity
3 10 21 15 Yes Search smaller capacity
4 10 15 12 No Search larger capacity
5 13 15 14 No Search larger capacity
6 15 15 - - Answer found

The first capacity that allows delivery within 5 days is 15.

Minimum ship capacity: 15

12. Understanding the Feasibility Check

For a capacity of 15, packages can be distributed across the days as follows:

Day Packages Total Weight
Day 1 1, 2, 3, 4, 5 15
Day 2 6, 7 13
Day 3 8 8
Day 4 9 9
Day 5 10 10

All packages are transported within exactly 5 days, and no day's total weight exceeds 15.

A capacity of 14 is insufficient because the greedy feasibility check requires more than 5 days. Therefore, 15 is the minimum valid capacity.

13. Another Example: Maximum Minimum Distance

Binary Search on Answer can also be used to maximize the minimum distance between selected positions.

Suppose we have several stalls arranged along a straight line and need to place a fixed number of cows in them. We want to maximize the minimum distance between any two placed cows.

Example

Stall positions:

positions = [1, 2, 4, 8, 9]

Number of cows:

k = 3

We want to place all 3 cows so that the minimum distance between any two cows is as large as possible.

Approach

  1. Sort the stall positions.
  2. Choose a candidate minimum distance.
  3. Place the first cow in the first stall.
  4. Place each next cow in the earliest stall that is at least the candidate distance away from the previous cow.
  5. If all cows can be placed, the candidate distance is possible.
  6. Try a larger distance to maximize the answer.

C++ Implementation

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool canPlaceCows(vector<int>& positions,
                  int cows,
                  int distance) {

    int placed = 1;

    int lastPosition = positions[0];

    for (int i = 1; i < positions.size(); i++) {

        if (positions[i] - lastPosition >= distance) {

            placed++;

            lastPosition = positions[i];

            if (placed == cows) {
                return true;
            }
        }
    }

    return false;
}

int maximumMinimumDistance(vector<int>& positions,
                           int cows) {

    sort(positions.begin(), positions.end());

    int low = 1;

    int high = positions.back() - positions.front();

    while (low < high) {

        int mid = low + (high - low + 1) / 2;

        if (canPlaceCows(positions, cows, mid)) {

            low = mid;
        }
        else {

            high = mid - 1;
        }
    }

    return low;
}

int main() {

    vector<int> positions = {1, 2, 4, 8, 9};

    int cows = 3;

    cout << "Maximum minimum distance: "
         << maximumMinimumDistance(positions, cows);

    return 0;
}

Output

Maximum minimum distance: 3

14. Time Complexity of Binary Search on Answer

Binary Search on Answer performs two major operations:

  1. Binary Search over the possible answer range.
  2. A feasibility check for every candidate answer.

If the answer range contains values from low to high, the number of Binary Search iterations is approximately:

O(log(high - low + 1))

If one feasibility check takes O(n) time, the total time complexity becomes:

O(n * log(high - low + 1))

For the shipping example, checking one capacity requires examining every package, so one feasibility check takes O(n).

Operation Time Complexity
Find minimum and maximum range O(n)
One feasibility check O(n)
Number of Binary Search iterations O(log R)
Overall time complexity O(n log R)

Here, R represents the size of the possible answer range. More precisely, R = high - low + 1.

15. Space Complexity

In the shipping example, the feasibility function uses only a few additional variables, such as the current load and required number of days.

The iterative Binary Search also uses only low, high, and mid.

Auxiliary Space Complexity: O(1)

This excludes the input array. If a problem requires copying or sorting data, the additional memory requirements depend on that implementation.

16. Common Problems Solved Using Binary Search on Answer

  • Book Allocation: Minimize the maximum number of pages assigned to a student.
  • Allocate Minimum Number of Pages: Find the smallest possible maximum workload.
  • Minimum Ship Capacity: Find the minimum capacity required to deliver packages within a time limit.
  • Aggressive Cows: Maximize the minimum distance between placed cows.
  • Koko Eating Bananas: Find the minimum eating speed needed to finish within a given time.
  • Smallest Divisor: Find the smallest divisor satisfying a given threshold.
  • Painter's Partition: Minimize the maximum workload assigned to painters.
  • Minimum Days to Make Bouquets: Find the minimum number of days required to make a required number of bouquets.

17. Binary Search on Answer vs Ordinary Binary Search

Feature Ordinary Binary Search Binary Search on Answer
Purpose Find a target element Find an optimal valid answer
Search Space Sorted collection Possible answer range
Comparison Compare target with middle element Check whether a candidate answer is feasible
Main Condition Sorted data Monotonic feasibility condition
Result Index or not found Minimum or maximum valid answer
Common Applications Searching in sorted arrays Optimization and allocation problems

18. Common Mistakes to Avoid

  • Applying Binary Search without checking whether the feasibility condition is monotonic.
  • Choosing incorrect minimum and maximum possible answers.
  • Writing an incorrect feasibility function.
  • Confusing the first valid answer with the last valid answer.
  • Using an incorrect middle-index calculation.
  • Updating low and high incorrectly, which may cause an infinite loop.
  • Forgetting to consider boundary cases.
  • Using int when the possible answer range or total sum may exceed its limit.
  • Forgetting that the feasibility check contributes to the overall time complexity.

19. Practice Questions

Basic Questions

  1. What is Binary Search on Answer?
  2. How is it different from ordinary Binary Search?
  3. What is monotonicity?
  4. What is a feasibility function?
  5. What is the difference between finding the first true and last true answer?

Intermediate Questions

  1. Explain how Binary Search can find the minimum ship capacity.
  2. How do you determine the search range in the shipping problem?
  3. Why is a monotonic condition necessary?
  4. Explain how the feasibility function works in the Aggressive Cows problem.
  5. Calculate the time complexity when each feasibility check takes O(n).

Programming Practice

  1. Implement Binary Search on Answer to find the minimum ship capacity.
  2. Solve the Book Allocation problem using Binary Search on Answer.
  3. Solve the Aggressive Cows problem.
  4. Find the minimum eating speed required to finish a collection of bananas within a given number of hours.
  5. Find the smallest divisor that satisfies a given threshold.
  6. Implement a function to find the first valid answer in a monotonic search space.
  7. Implement a function to find the last valid answer in a monotonic search space.

20. Key Takeaways

  • Binary Search on Answer is used for optimization problems.
  • It searches through a range of possible answers rather than array indexes.
  • A monotonic feasibility condition is required.
  • A feasibility function determines whether a candidate answer is valid.
  • First True Binary Search finds the smallest valid answer.
  • Last True Binary Search finds the largest valid answer.
  • The total complexity depends on both the search range and the feasibility check.
  • It is widely used in allocation, scheduling, distance, capacity, and speed problems.
Next Topic: In the next lesson, we will study Lower Bound and Upper Bound. These are important Binary Search techniques used to find insertion positions and the first or last positions satisfying specific comparison conditions.
Scroll to Top