Bird
Raised Fist0
DSA C++programming

Binary Search on Answer Technique in DSA C++

Choose your learning style10 modes available
Mental Model
We guess an answer and check if it works, then adjust the guess up or down until we find the best answer.
Analogy: Imagine trying to find the right temperature to bake a cake by guessing a temperature, baking, and checking if it's done. If it's undercooked, increase the temperature; if burnt, decrease it. Repeat until perfect.
low ← mid -> high
[low]----[mid]----[high]
 ↑      ↑       ↑
 guess  check   limit
Dry Run Walkthrough
Input: array: [2, 3, 5, 9, 14], max allowed sum per subarray = 10; find minimum largest sum to split array into subarrays
Goal: Find the smallest maximum sum possible when splitting the array into subarrays so that no subarray sum exceeds this value
Step 1: Set low to max element 14, high to sum 33, guess mid = (14+33)/2 = 23
low=14, mid=23, high=33
Why: We start searching between the largest single element and total sum
Step 2: Check if array can be split with max subarray sum ≤ 23
Subarrays: [2,3,5,9] sum=19 ≤ 23, [14] sum=14 ≤ 23
Why: 23 works because we can split into 2 subarrays without exceeding 23
Step 3: Since 23 works, try smaller max sum by setting high = mid = 23
low=14, high=23
Why: Try to find smaller max sum to optimize answer
Step 4: Guess mid = (14+23)/2 = 18, check feasibility
Check subarrays with max sum ≤ 18
Why: Test if smaller max sum 18 is possible
Step 5: Split: [2,3,5,9] sum=19 > 18, so split earlier: [2,3,5] sum=10 ≤ 18, next subarray [9,14] sum=23 > 18
Cannot split into valid subarrays with max sum ≤ 18
Why: 18 too small, need to increase low
Step 6: Set low = mid + 1 = 19
low=19, high=23
Why: Increase low to find feasible max sum
Step 7: Guess mid = (19+23)/2 = 21, check feasibility
Check subarrays with max sum ≤ 21
Why: Test if 21 works
Step 8: Split: [2,3,5,9] sum=19 ≤ 21, [14] sum=14 ≤ 21, works
Feasible with max sum 21
Why: Try smaller max sum by setting high = 21
Step 9: Set high = 21
low=19, high=21
Why: Try to find smaller max sum
Step 10: Guess mid = (19+21)/2 = 20, check feasibility
Check subarrays with max sum ≤ 20
Why: Test if 20 works
Step 11: Split: [2,3,5,9] sum=19 ≤ 20, [14] sum=14 ≤ 20, works
Feasible with max sum 20
Why: Try smaller max sum by setting high = 20
Step 12: Set high = 20
low=19, high=20
Why: Try to find smaller max sum
Step 13: Guess mid = (19+20)/2 = 19, check feasibility
Check subarrays with max sum ≤ 19
Why: Test if 19 works
Step 14: Split: [2,3,5,9] sum=19 ≤ 19, [14] sum=14 ≤ 19, works
Feasible with max sum 19
Why: Try smaller max sum by setting high = 19
Step 15: Set high = 19
low=19, high=19
Why: low equals high, search ends
Result:
Final answer: 19
Array split with max subarray sum 19: [2,3,5,9] and [14]
Annotated Code
DSA C++
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;

bool canSplit(const vector<int>& nums, int maxSum) {
    int currentSum = 0;
    int subarrays = 1;
    for (int num : nums) {
        if (num > maxSum) return false; // single element too big
        if (currentSum + num <= maxSum) {
            currentSum += num; // add to current subarray
        } else {
            subarrays++; // start new subarray
            currentSum = num;
        }
    }
    return subarrays <= 2; // check if splits within allowed count
}

int binarySearchAnswer(const vector<int>& nums) {
    int low = *max_element(nums.begin(), nums.end());
    int high = accumulate(nums.begin(), nums.end(), 0);
    while (low < high) {
        int mid = low + (high - low) / 2;
        if (canSplit(nums, mid)) {
            high = mid; // try smaller max sum
        } else {
            low = mid + 1; // increase min sum
        }
    }
    return low;
}

int main() {
    vector<int> nums = {2, 3, 5, 9, 14};
    int result = binarySearchAnswer(nums);
    cout << result << endl;
    return 0;
}
if (num > maxSum) return false; // single element too big
guard against impossible max sum smaller than any element
if (currentSum + num <= maxSum) { currentSum += num; } else { subarrays++; currentSum = num; }
split array when adding next element exceeds maxSum
return subarrays <= 2;
check if number of subarrays is within allowed limit
while (low < high) { int mid = low + (high - low) / 2; if (canSplit(nums, mid)) { high = mid; } else { low = mid + 1; } }
binary search on answer space adjusting low/high based on feasibility
OutputSuccess
19
Complexity Analysis
Time: O(n log S) because each binary search step does a linear check over n elements, and S is the range between max element and sum
Space: O(1) because only a few variables are used, no extra data structures proportional to input
vs Alternative: Naive approach tries all sums from max element to total sum, which is O(n * S) and much slower
Edge Cases
Array with one element
Returns that element as minimum max sum
DSA C++
if (num > maxSum) return false;
All elements equal
Splits evenly, binary search finds exact max sum
DSA C++
while (low < high) { ... }
Max sum smaller than any element
canSplit returns false immediately
DSA C++
if (num > maxSum) return false;
When to Use This Pattern
When a problem asks for an optimal numeric answer that can be checked for feasibility, use binary search on the answer space to efficiently find it.
Common Mistakes
Mistake: Not setting low to max element, causing invalid guesses
Fix: Initialize low as the maximum element in the array
Mistake: Not checking feasibility correctly, allowing invalid splits
Fix: Implement canSplit to count subarrays and compare with allowed limit
Summary
Finds the smallest value that satisfies a feasibility condition by guessing and checking.
Use when the answer is numeric and can be tested with a yes/no feasibility function.
The key is to binary search over the answer range, not the input data.

Practice

(1/5)
1. What is the main idea behind the Binary Search on Answer technique?
easy
A. Searching for the answer by repeatedly dividing the search space based on feasibility
B. Sorting the array before applying binary search
C. Using binary search to find an element in a sorted array
D. Applying binary search only on arrays with unique elements

Solution

  1. Step 1: Understand the problem context

    Binary Search on Answer is used when the answer lies within a range and we can check feasibility for a candidate answer.
  2. Step 2: Apply binary search on the answer range

    We repeatedly pick a middle value and check if it satisfies the problem's conditions, narrowing the search space accordingly.
  3. Final Answer:

    Searching for the answer by repeatedly dividing the search space based on feasibility -> Option A
  4. Quick Check:

    Binary Search on Answer = feasibility check [OK]
Hint: Think of binary search on answer as guessing and checking [OK]
Common Mistakes:
  • Confusing it with normal binary search on arrays
  • Not checking feasibility properly
  • Trying to apply it on unsorted data without a valid range
2. Which of the following is the correct syntax to start a binary search on answer for an integer range low to high in C++?
easy
A. while (low <= high) { int mid = (low + high) / 2; }
B. for (int mid = low; mid <= high; mid++) { }
C. while (low < high) { int mid = low + (high - low) / 2; }
D. if (low < high) { mid = (low + high) / 2; }

Solution

  1. Step 1: Identify the correct loop condition

    Binary search typically uses a loop with condition low < high to avoid infinite loops and handle edge cases.
  2. Step 2: Calculate mid safely

    Using mid = low + (high - low) / 2 prevents integer overflow compared to (low + high) / 2.
  3. Final Answer:

    while (low < high) { int mid = low + (high - low) / 2; } -> Option C
  4. Quick Check:

    Safe mid calculation with proper loop [OK]
Hint: Use low + (high - low)/2 to avoid overflow [OK]
Common Mistakes:
  • Using <= in loop causing infinite loops
  • Calculating mid as (low + high)/2 risking overflow
  • Using for loop instead of while for binary search
3. Consider the following code snippet that uses binary search on answer to find the minimum maximum load for dividing an array into k subarrays:
bool canDivide(const vector<int>& arr, int k, int maxLoad) {
    int currentSum = 0, count = 1;
    for (int num : arr) {
        if (num > maxLoad) return false;
        if (currentSum + num > maxLoad) {
            count++;
            currentSum = num;
        } else {
            currentSum += num;
        }
    }
    return count <= k;
}

int binarySearchAnswer(const vector<int>& arr, int k) {
    int low = 0, high = 0;
    for (int num : arr) high += num;
    while (low < high) {
        int mid = low + (high - low) / 2;
        if (canDivide(arr, k, mid)) high = mid;
        else low = mid + 1;
    }
    return low;
}

int main() {
    vector<int> arr = {7, 2, 5, 10, 8};
    int k = 2;
    cout << binarySearchAnswer(arr, k) << endl;
}

What is the output of this program?
medium
A. 15
B. 18
C. 20
D. 22

Solution

  1. Step 1: Understand the problem and code

    The code finds the minimum maximum sum when dividing the array into 2 subarrays. The total sum is 7+2+5+10+8=32.
  2. Step 2: Trace binary search on answer

    Check mid values and feasibility:
    - mid=16: canDivide returns true (possible, e.g., subarrays sums 14 and 18)
    - mid=15: canDivide returns true (possible, e.g., subarrays sums 14 and 15)
    - mid=14: canDivide returns false (cannot split into 2 with max sum 14)
    Binary search narrows down to 15 as minimum max load.
  3. Final Answer:

    15 -> Option A
  4. Quick Check:

    Minimum max load = 15 [OK]
Hint: Sum array, binary search between 0 and sum [OK]
Common Mistakes:
  • Not checking if single element > mid
  • Incorrectly updating low and high
  • Misunderstanding feasibility function
4. The following code attempts to find the smallest maximum weight capacity to ship packages within D days using binary search on answer. Identify the bug:
bool canShip(const vector<int>& weights, int D, int capacity) {
    int days = 1, currentLoad = 0;
    for (int w : weights) {
        if (w > capacity) return false;
        if (currentLoad + w > capacity) {
            days++;
            currentLoad = w;
        } else {
            currentLoad += w;
        }
    }
    return days <= D;
}

int shipWithinDays(const vector<int>& weights, int D) {
    int low = 0, high = accumulate(weights.begin(), weights.end(), 0);
    while (low <= high) {
        int mid = low + (high - low) / 2;
        if (canShip(weights, D, mid)) high = mid - 1;
        else low = mid + 1;
    }
    return low;
}
medium
A. The loop condition should be low < high instead of low <= high
B. The mid calculation can cause integer overflow
C. The canShip function does not handle empty weights array
D. The initial value of low should be the maximum weight in the array, not 0

Solution

  1. Step 1: Analyze initial search range

    Low should start at the maximum single package weight because capacity cannot be less than the heaviest package.
  2. Step 2: Identify impact of wrong low value

    Starting low at 0 causes unnecessary checks and may cause incorrect results or longer runtime.
  3. Final Answer:

    The initial value of low should be the maximum weight in the array, not 0 -> Option D
  4. Quick Check:

    Low = max(weights) [OK]
Hint: Low must be max element, high sum of all [OK]
Common Mistakes:
  • Starting low at 0 instead of max element
  • Using <= in loop causing off-by-one errors
  • Ignoring edge cases with large weights
5. You want to find the minimum time required to complete n tasks using m machines, where each machine can complete one task in a fixed time given by array times. You can assign multiple tasks to a machine but tasks are done sequentially. Using binary search on answer, which approach correctly finds the minimum time to finish all tasks?

Choose the correct approach:
hard
A. Binary search on number of machines from 1 to m, checking if tasks can be done in fixed time
B. Binary search on time range from 0 to max(times) * n, and check if total tasks done by all machines in mid time is at least n
C. Sort times and pick the machine with minimum time multiplied by n
D. Use binary search on tasks from 1 to n, checking if tasks fit in given time

Solution

  1. Step 1: Define search space for binary search

    The minimum time is 0 and maximum time is max machine time * n tasks (worst case all tasks on slowest machine).
  2. Step 2: Check feasibility at mid time

    Calculate total tasks all machines can complete in mid time by summing floor(mid / times[i]). If total tasks >= n, mid time is feasible.
  3. Step 3: Narrow search space

    If feasible, try smaller time by setting high = mid; else low = mid + 1.
  4. Final Answer:

    Binary search on time range from 0 to max(times) * n, and check if total tasks done by all machines in mid time is at least n -> Option B
  5. Quick Check:

    Binary search on time with feasibility check [OK]
Hint: Search time range, count tasks done at mid [OK]
Common Mistakes:
  • Binary searching on machines instead of time
  • Not summing tasks correctly for feasibility
  • Ignoring sequential task processing per machine
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard