A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/dsa/binary-search-on-answer-tutorial-with-problems/ below:

Binary Search on Answer Tutorial with Problems

Binary Search on Answer Tutorial with Problems

Last Updated : 23 Jul, 2025

Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and reduce the search space accordingly. Prerequisite: Binary Search

Let's understand this via an example:

Given a positive number X, the task is to find out the maximum positive integer that satisfies the given equation: n2 < X

Input: X = 101
Output: 10

Inefficient approach (Finding answer randomly):

Illustrations:

Take n = 4: n2 = 16 and 16 < 101 and ans < n , so ans = 4.
then take n = 2: n2 = 4 and 4 < 101 but ans > n so continue.
then take n = 6: n2 = 36 and 36 < 101 and ans < n so ans = 6.
then take n = 15: n2 = 225 and 225 > 101 so ans = 6.
.
.
.
.
and so on...

We can see if we repeatedly do this process we will reach closer to our answer !! But is this an efficient way ?? "No". By using random number we are calculating the same values of n multiple times which will increase out complexity unnecessarily.

Brute force approach (Finding answer linearly):

In this approach we will only calculate the value of n single time and move forward and if any point we find the equation is true we update our answer.

Illustration:

Initialize ans = 0.

Take n = 1: 12 < 101 , ans = 1
take n = 2: 22 < 101 , ans =2
take n = 3: 32 < 101 , ans =3
.
.
take n = 10: 102 < 101 , ans = 10
take n = 11: 112 > 101 , ans = 10 .
.
.
take n = 101: 1012 > 101 , ans = 10.

This is better approach than previous one because now our time complexity will be O(X) only, because we are checking answer for each value between 0 to X .

Optimized approach ( Binary Search on answer ):

Now we will find our answer using the monotonic behaviour of the equation !!

Illustration:

By following this approach we can find out our answer in log (X) time which is far better than randomly choosing the value or linearly choosing the values.

This approach is called Binary Search on answer!!

How to identify Binary Search on answer:

Whenever we are able to identify that the answer of the problem lies between in a range L to R and there is a Monotonic Behaviour of answer in range L to R then we can think to apply binary search on answer.

Way to approach this Question:

1. Finding out the Search Space:

2. Finding out the monotonic relation in the problem:

Steps to Solve the problem:

This searching technique of answer is called Binary Search on answer.

Below is the code of above idea:

C++
// C++ code for the above approach:
#include <iostream>
using namespace std;

// Drivers code
int main()
{

    int X = 101;

    int lo = 0;
    int hi = X;

    // When there is no good index
    // we will return -1
    int answer = -1;

    // Applying Binary Search
    while (lo <= hi) {
        int mid = (lo + hi) / 2;
        if (mid * mid < X) {

            // Store the good index
            answer = mid;
            lo = mid + 1;
        }
        else {
            hi = mid - 1;
        }
    }

    cout << "Value which satisfies the equation : "
         << answer << endl;
}
Java
public class SquareRootBinarySearch {
    public static void main(String[] args) {
        int X = 101; // The number for which we want to find the square root
        int lo = 0; // Initialize the lower bound of the search range
        int hi = X; // Initialize the upper bound of the search range
        int answer = -1; // Initialize the answer variable

        // Perform binary search to find the square root
        while (lo <= hi) {
            int mid = (lo + hi) / 2; // Calculate the middle value

            // Check if the square of the middle value is less than X
            if (mid * mid < X) {
                answer = mid; // Update the answer to the current middle value
                lo = mid + 1; // Update the lower bound for the next iteration
            } else {
                hi = mid - 1; // Update the upper bound for the next iteration
            }
        }

        System.out.println("Value which satisfies the equation: " + answer);
    }
}
Python
if __name__ == "__main__":
    x = 101  # The number for which to find the square root
    lo = 0  # Initialize the lower bound of the search range
    hi = x  # Initialize the upper bound of the search range
    answer = -1  # Initialize the answer variable

    # Perform binary search to find the square root
    while lo <= hi:
        mid = (lo + hi) // 2  # Calculate the middle value

        # Check if the square of the middle value is less than x
        if mid * mid < x:
            answer = mid  # Update the answer to the current middle value
            lo = mid + 1  # Update the lower bound for the next iteration
        else:
            hi = mid - 1  # Update the upper bound for the next iteration
   
    print("Value which satisfies the equation:", answer)
C#
using System;

class Program
{
    static void Main()
    {
        int X = 101;

        int lo = 0;
        int hi = X;

        // When there is no good index
        // we will return -1
        int answer = -1;

        // Applying Binary Search
        while (lo <= hi)
        {
            int mid = (lo + hi) / 2;
            if (mid * mid < X)
            {
                // Store the good index
                answer = mid;
                lo = mid + 1;
            }
            else
            {
                hi = mid - 1;
            }
        }

        Console.WriteLine("Value which satisfies the equation: " + answer);
    }
}
JavaScript
// Function to find the largest integer whose square is less than X
function findSqrt(X) {
    let lo = 0;         // Lower bound of search range
    let hi = X;         // Upper bound of search range
    let answer = -1;    // Variable to store the result

    // Binary Search loop
    while (lo <= hi) {
        let mid = Math.floor((lo + hi) / 2);  // Calculate mid value

        // Check if the square of mid is less than X
        if (mid * mid < X) {
            answer = mid;   // Store the current mid value as the potential answer
            lo = mid + 1;   // Update the lower bound to search for a larger number
        } else {
            hi = mid - 1;   // Update the upper bound to search for a smaller number
        }
    }

    return answer;   // Return the largest integer whose square is less than X
}

// Main function to demonstrate the findSqrt function
let X = 101;        // Input number
let result = findSqrt(X);   // Call the findSqrt function
console.log(`Value which satisfies the equation: ${result}`);   // Display the result

Output
Value which satisfies the equation : 10

Time Complexity: O(logN)
Auxiliary Complexity: O(1)

Binary Search on Min of max or Max of min problems:

In most of the questions where question asks about Find maximum value of something in minimum X operations or Minimum value of something by maximizing some other parameter more often these questions are Binary Search on Answer.

Let's Take a question for better understanding:

Problem Statement:

Given N boxes and and each box contains different kind of fruits also each box contains arr[i] fruits. In one hour you can select any one type of fruit and eat at most X fruits of that particular type. You Have exactly H hours to finish all the fruits, the task is to find out the minimum value of X such that you can finish all the fruits in maximum H hours.

Note: H is always greater than or equal to N .

Example:

Input: N = 5 , arr[] = [ 2, 4, 2, 4, 5] , H=8
Output: 3
Explanation:

Input: N = 1, arr[] = [12], H = 2
Output: 6

Approach: To solve the problem follow the below idea:

Idea: We can apply binary Search on answer to solve this problem.

Search Space:

Monotonic Relation:

If we can eat X amount of fruit in one hour and it takes T hour to finish all the fruits.

Now we know the search space and monotonic relation so we just have to iterate over the ' arr ' array and find total time we will take to eat all fruits if current speed of eating the fruits in one hour is X, if time taken is less than H we can shift our high limit to x-1, otherwise shift low = x+1.

By following above idea we can find out our valid minimum possible speed by which we can eat all fruit in H hour.

Steps to solve the problem:

Below is the implementation for the above approach:

C++
// C++ code for the above approach:
#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int minXvalue(vector<int>& arr, int H)
    {
        int X = *max_element(arr.begin(), arr.end());
        int lo = 0, hi = X;
        while (lo <= hi) {
            int x = (lo + hi) / 2;
            int req_time = 0;
            for (auto val : arr) {

                // ceil value
                req_time += (val + x - 1) / x;
            }
            if (req_time <= H) {
                X = x;
                hi = x - 1;
            }
            else {
                lo = x + 1;
            }
        }
        return X;
    }
};

// Drivers code
int main()
{
    Solution solution;
    vector<int> arr = { 8, 11, 18, 20 };
    int h = 10;
    int result = solution.minXvalue(arr, h);

    // Function Call
    cout << "Minimum value of X will be : " << result
         << endl;
    return 0;
}
Java
import java.io.*;
import java.util.Arrays;

class Solution {
    public static int minxValue(int[] arr, int H) {
        int X = Arrays.stream(arr).max().getAsInt();
        int lo = 0, hi = X;

        while (lo <= hi) {
            int x = (lo + hi) / 2;
            int reqTime = 0;

            for (int val : arr) {
                // ceil value
                reqTime += (val + x - 1) / x;
            }

            if (reqTime <= H) {
                X = x;
                hi = x - 1;
            } else {
                lo = x + 1;
            }
        }

        return X;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[] arr = {8, 11, 18, 20};
        int h = 10;
        int result = solution.minxValue(arr, h);

        // Function Call
        System.out.println("Minimum value of X will be : " + result);
    }
}
//This code is contributed by Rohit Singh
Python
class Solution:
    def minXvalue(self, arr, H):
        X = max(arr)
        lo, hi = 0, X
        while lo <= hi:
            x = (lo + hi) // 2
            req_time = 0
            for val in arr:
                # ceil value
                req_time += (val + x - 1) // x
            if req_time <= H:
                X = x
                hi = x - 1
            else:
                lo = x + 1
        return X

# Driver code
if __name__ == "__main__":
    solution = Solution()
    arr = [8, 11, 18, 20]
    h = 10
    result = solution.minXvalue(arr, h)

    # Function Call
    print("Minimum value of X will be:", result)
    

# by phasing17
C#
using System;
using System.Collections.Generic;
using System.Linq; // Import LINQ namespace for Max() method

class Solution
{
    // Function to find the minimum X value
    public int MinXValue(List<int> arr, int H)
    {
        // Finding the maximum value in the list 'arr'
        int X = arr.Max();

        // Binary search for the minimum X value that satisfies the condition
        int lo = 0, hi = X;
        while (lo <= hi)
        {
            int x = (lo + hi) / 2;
            int reqTime = 0;

            // Calculating the total time required for each element in 'arr'
            foreach (var val in arr)
            {
                // ceil value calculation for time
                reqTime += (val + x - 1) / x;
            }

            // Checking if the total time is less than or equal to H
            if (reqTime <= H)
            {
                X = x;
                hi = x - 1; // Update the upper bound
            }
            else
            {
                lo = x + 1; // Update the lower bound
            }
        }

        // Return the minimum X value
        return X;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Solution solution = new Solution();
        List<int> arr = new List<int> { 8, 11, 18, 20 };
        int h = 10;

        // Finding the minimum X value
        int result = solution.MinXValue(arr, h);

        // Outputting the result
        Console.WriteLine($"Minimum value of X will be : {result}");
    }
}
JavaScript
class Solution {
    // Function to find the minimum X value
    minXValue(arr, H) {
        // Finding the maximum value in the array 'arr'
        let X = Math.max(...arr);

        // Binary search for the minimum X value that satisfies the condition
        let lo = 0, hi = X;
        while (lo <= hi) {
            let x = Math.floor((lo + hi) / 2);
            let reqTime = 0;

            // Calculating the total time required for each element in 'arr'
            for (let val of arr) {
                // ceil value calculation for time
                reqTime += Math.ceil(val / x);
            }

            // Checking if the total time is less than or equal to H
            if (reqTime <= H) {
                X = x;
                hi = x - 1; // Update the upper bound
            } else {
                lo = x + 1; // Update the lower bound
            }
        }

        // Return the minimum X value
        return X;
    }
}

// Create a new instance of Solution class
let solution = new Solution();

// Given input array and H value
let arr = [8, 11, 18, 20];
let h = 10;

// Finding the minimum X value
let result = solution.minXValue(arr, h);

// Outputting the result
console.log(`Minimum value of X will be: ${result}`);

Output
Minimum value of X will be : 7

Time Complexity: O(N*logN)
Auxiliary Space: O(1)

Keywords to find out Binary Search Question: Practice Questions:

For Better Understanding of the above topic we highly recommend you to solve these problems:

Problem

Post Link

Practice Link

1) Time Crunch Challenge

Link

2) Find minimum subarray length to reduce frequency

Link

3) Maximize minimum sweetness in cake cutting

Link

4) Maximize minimum element of an Array using operations

Link

5) Maximize the minimum element and return it

Link

6) Find the maximum value of the K-th smallest usage value in Array

Link

Link

7) Assign stalls to K cows to maximize the minimum distance between them

Link

Link

8) Minimum time to complete at least K tasks when everyone rest after each task

Link

9) Maximum count of integers to be chosen from given two stacks having sum at most K

Link

10 ) Find the row up to which there are at least K stars in the Diamond Pattern

Link



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4