Bird
Raised Fist0
DSA Cprogramming~20 mins

Binary Search on Answer Technique in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Binary Search on Answer Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Binary Search on Answer for Minimum Maximum Subarray Sum
What is the output of the following code that uses binary search on answer to find the minimum largest sum among subarrays?
DSA C
int canSplit(int* nums, int numsSize, int maxSum, int m) {
    int currentSum = 0, count = 1;
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] > maxSum) return 0;
        if (currentSum + nums[i] > maxSum) {
            count++;
            currentSum = nums[i];
            if (count > m) return 0;
        } else {
            currentSum += nums[i];
        }
    }
    return 1;
}

int splitArray(int* nums, int numsSize, int m) {
    int left = 0, right = 0;
    for (int i = 0; i < numsSize; i++) right += nums[i];
    int result = right;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (canSplit(nums, numsSize, mid, m)) {
            result = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return result;
}

#include <stdio.h>
int main() {
    int nums[] = {7, 2, 5, 10, 8};
    int m = 2;
    int result = splitArray(nums, 5, m);
    printf("%d\n", result);
    return 0;
}
A18
B25
C20
D15
Attempts:
2 left
💡 Hint
Think about how the binary search narrows down the maximum allowed subarray sum.
🧠 Conceptual
intermediate
1:30remaining
Understanding the Role of the Check Function in Binary Search on Answer
In the binary search on answer technique, what is the main purpose of the 'check' function?
ATo calculate the midpoint between low and high values
BTo verify if a guessed answer satisfies the problem constraints
CTo sort the input data before binary searching
DTo store intermediate results for memoization
Attempts:
2 left
💡 Hint
Think about how binary search decides to move left or right.
🔧 Debug
advanced
2:00remaining
Identify the Error in Binary Search on Answer Implementation
What error will the following code produce when running binary search on answer to find the minimum maximum time to complete tasks?
DSA C
int canFinish(int* tasks, int tasksSize, int maxTime, int workers) {
    int count = 1, currentTime = 0;
    for (int i = 0; i < tasksSize; i++) {
        if (tasks[i] > maxTime) return 0;
        if (currentTime + tasks[i] > maxTime) {
            count++;
            currentTime = tasks[i];
            if (count > workers) return 0;
        } else {
            currentTime += tasks[i];
        }
    }
    return 1;
}

int minTime(int* tasks, int tasksSize, int workers) {
    int left = 0, right = 0;
    for (int i = 0; i < tasksSize; i++) right += tasks[i];
    int result = right;
    while (left < right) {
        int mid = (left + right) / 2;
        if (canFinish(tasks, tasksSize, mid, workers)) {
            result = mid;
            right = mid - 1;
        } else {
            left = mid + 1;
        }
    }
    return result;
}

#include <stdio.h>
int main() {
    int tasks[] = {3, 6, 7, 11};
    int workers = 2;
    int answer = minTime(tasks, 4, workers);
    printf("%d\n", answer);
    return 0;
}
ASegmentation fault due to invalid array access
BCompilation error due to missing header
CCorrect output: 18
DInfinite loop due to incorrect binary search update
Attempts:
2 left
💡 Hint
Check how the binary search updates left and right pointers.
🚀 Application
advanced
2:00remaining
Applying Binary Search on Answer to Allocate Books Problem
Given an array of book pages and number of students, binary search on answer is used to find the minimum maximum pages assigned to a student. Which of the following outputs is correct for input pages = [12, 34, 67, 90], students = 2?
A113
B67
C90
D156
Attempts:
2 left
💡 Hint
Try splitting the books into 2 parts minimizing the maximum sum.
🧠 Conceptual
expert
1:30remaining
Why is Binary Search on Answer Efficient for Optimization Problems?
Why does binary search on answer technique efficiently solve optimization problems where the answer lies within a numeric range?
ABecause it reduces the search space exponentially by checking feasibility at midpoints
BBecause it sorts the input data first to apply binary search
CBecause it uses recursion to explore all possible answers
DBecause it stores all intermediate answers in a hash map
Attempts:
2 left
💡 Hint
Think about how binary search halves the search space each step.

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 only on sorted arrays
D. Applying binary search to find the maximum element in an array

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: Explain the technique

    We repeatedly pick a middle value in the answer range and check if it satisfies the problem's conditions, then narrow the range 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 = Divide and check feasibility [OK]
Hint: Think of answer range, not array elements, for binary search [OK]
Common Mistakes:
  • Confusing it with normal binary search on arrays
  • Trying to apply without a feasibility check
  • Assuming answer must be in the input array
2. Which of the following is the correct syntax to start a binary search on answer in C for an integer answer between low and high?
easy
A. for (int mid = low; mid <= high; mid++) { /* check feasibility */ }
B. do { mid = (low + high) / 2; /* check feasibility */ } while (low < high);
C. if (low < high) { mid = (low + high) / 2; /* check feasibility */ }
D. while (low <= high) { int mid = (low + high) / 2; /* check feasibility */ }

Solution

  1. Step 1: Identify the binary search loop structure

    Binary search uses a while loop with condition low <= high to narrow the search space.
  2. Step 2: Confirm calculation of mid and feasibility check

    Mid is calculated as (low + high) / 2 inside the loop, then feasibility is checked to adjust low or high.
  3. Final Answer:

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

    Binary search loop = while(low <= high) [OK]
Hint: Use while loop with low <= high for binary search [OK]
Common Mistakes:
  • Using for loop instead of while
  • Incorrect loop condition like low < high
  • Not updating low or high inside loop
3. Consider the following C code snippet using binary search on answer to find the minimum maximum load to split an array into m subarrays:
int canSplit(int* arr, int n, int m, int maxLoad) {
    int count = 1, currentSum = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] > maxLoad) return 0;
        if (currentSum + arr[i] > maxLoad) {
            count++;
            currentSum = arr[i];
        } else {
            currentSum += arr[i];
        }
    }
    return count <= m;
}

int binarySearchAnswer(int* arr, int n, int m) {
    int low = 0, high = 0;
    for (int i = 0; i < n; i++) high += arr[i];
    int ans = high;
    while (low <= high) {
        int mid = (low + high) / 2;
        if (canSplit(arr, n, m, mid)) {
            ans = mid;
            high = mid - 1;
        } else {
            low = mid + 1;
        }
    }
    return ans;
}

int main() {
    int arr[] = {7, 2, 5, 10, 8};
    int n = 5, m = 2;
    printf("%d", binarySearchAnswer(arr, n, m));
    return 0;
}
What is the output of this program?
medium
A. 18
B. 15
C. 20
D. 10

Solution

  1. Step 1: Understand the problem and code logic

    The code finds the minimum maximum load to split the array into 2 subarrays so that the largest sum among subarrays is minimized.
  2. Step 2: Dry run with given array

    Possible splits: - [7,2,5] and [10,8] max sums 14 and 18 -> max 18 - [7,2] and [5,10,8] max sums 9 and 23 -> max 23 - [7] and [2,5,10,8] max sums 7 and 25 -> max 25 Minimum max load is 18.
  3. Final Answer:

    18 -> Option A
  4. Quick Check:

    Minimum max load = 18 [OK]
Hint: Check feasibility by simulating splits, pick minimal max sum [OK]
Common Mistakes:
  • Choosing sum of all elements as answer
  • Not considering feasibility function logic
  • Confusing minimum max load with total sum
4. The following code tries to find the minimum maximum time to complete tasks by binary searching on answer. Identify the bug:
int canComplete(int* tasks, int n, int m, int maxTime) {
    int count = 1, currentTime = 0;
    for (int i = 0; i < n; i++) {
        if (tasks[i] > maxTime) return 0;
        if (currentTime + tasks[i] >= maxTime) {
            count++;
            currentTime = tasks[i];
        } else {
            currentTime += tasks[i];
        }
    }
    return count <= m;
}
medium
A. The count variable should start from 0, not 1
B. The condition should be currentTime + tasks[i] > maxTime, not >= maxTime
C. The function should return count >= m instead of count <= m
D. The loop should run from i = 1 instead of i = 0

Solution

  1. Step 1: Analyze the feasibility condition

    The condition currentTime + tasks[i] >= maxTime causes a new segment even when sum equals maxTime, which is incorrect.
  2. Step 2: Correct the condition

    It should be currentTime + tasks[i] > maxTime to start a new segment only when sum exceeds maxTime.
  3. Final Answer:

    The condition should be currentTime + tasks[i] > maxTime, not >= maxTime -> Option B
  4. Quick Check:

    Use > for splitting condition, not >= [OK]
Hint: Use strict greater than (>) to split segments [OK]
Common Mistakes:
  • Using >= causes extra segments
  • Starting count from 0 instead of 1
  • Returning wrong comparison for count and m
5. You want to find the minimum maximum height to cut trees so that the total wood collected is at least m units. Given an array trees[] of heights, which approach correctly applies binary search on answer to solve this problem?
hard
A. Set low = min height, high = max height; check if sum of all trees is >= m; adjust low or high accordingly
B. Sort trees, then binary search for the tree with height closest to m
C. Set low = 0, high = max height in trees; check if cutting at mid yields enough wood; adjust low or high accordingly
D. Use binary search on the array indices to find the tree that yields maximum wood

Solution

  1. Step 1: Define the search space for cutting height

    The cutting height can vary from 0 to the tallest tree height.
  2. Step 2: Check feasibility by summing wood collected at mid height

    For a candidate mid, sum wood = sum of (tree height - mid) if positive; check if sum >= m.
  3. Step 3: Adjust search space based on feasibility

    If enough wood is collected, try higher cut (low = mid + 1) to minimize cut height; else lower cut (high = mid - 1).
  4. Final Answer:

    Set low = 0, high = max height in trees; check if cutting at mid yields enough wood; adjust low or high accordingly -> Option C
  5. Quick Check:

    Binary search on cut height range with feasibility check [OK]
Hint: Binary search on cutting height, not on tree indices [OK]
Common Mistakes:
  • Binary searching on sorted array instead of answer range
  • Using sum of all trees without cutting logic
  • Confusing indices with answer values
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