Open In App

Binary Search on Answer Tutorial with Problems

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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):

  • Initialize ans = 0 then take one element randomly from 0 to 101
  • Check if this number satisfies the equation or not and update the answer.

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 .

  • We can observe a monotonic behaviour in this method that before n=10 each value satisfy the equation but after n = 10 each value gives false for the equation.
  • We know the equation is monotonic and we know the search space so we now will think about finding our answer using these two properties !!

Optimized approach ( Binary Search on answer ):

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

  • Search space: Lower limit = 0, High limit = 101
  • Initial answer = 0 .

Illustration:

  • Take n = 50: 502 > 101 , ans = 0 , lower limit = 0 and hight limit = 49 ( Because we know if 50 does not satisfy our equation then values greater than 50 will not provide us valid answer ).
  • Taking n = 25 (mid value of lower lim. and high lim.) : 252 < 101 , ans = 0 , lower limit = 0 and high limit = 24.
  • Taking n = 12: 122 > 101 , ans = 0 , lower limit = 0 and high limit = 11.
  • Taking n = 5: 52 < 101 , ans = 5 , lower limit = 6 and high limit = 11 (Because we know if n=5 satisfy the equation then values less than 5 also give the valid answer).
  • Taking n = 8: 82 < 101 , ans = 8 , lower limit = 9 and high limit = 11 .
  • Taking n = 10: 102 < 101 , ans = 10 , lower limit = 11 and high limit = 11.
  • Taking n = 11: 112 > 101 , ans = 10 , lower limit = 11 and high limit = 10.

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:

  • We are Given a number X and also given numbers are positive
  • Finding value of L [ lower limit of search space ]:
    • We have to think about the minimum value which can satisfy the above equation!!
    • in the above problem it will be 0 because it is the minimum non negative value which satisfy the equation.
  • Finding value of R [ upper limit of search space]:
    • We have to think about the maximum value which can satisfy the above equation!!
    • in above problem it will be X because any value which is greater than X can never satisfy the equation .

2. Finding out the monotonic relation in the problem:

  • Given equation : n2 < X .
  • lets say our maximum valued integer is ‘K’ which satisfies the given equation , then we know that values < K will return True for the above inequality and values greater than K will give false for the same.
  • so this shows our relation is monotonic in nature.

Steps to Solve the problem:

  • Initialize our low and high values as 0 and X.
  • While low<= high, do the following:
  • Find mid value and check its validity for the equation
  • If mid*mid < X:
    • Store the value of mid as our valid answer
    • And reduce search space by updating low = mid+1
  • Else, reduce search space by moving high = mid – 1
  • At the end return the valid answer.

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);
    }
}
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
Python3
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)

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:

  • hour = 1 : eat fruit at index = 0 , so after an hour arr = [ 0 , 4 , 2 , 4 , 5].
  • hour = 2: eat fruit at index = 1 , so after an hour arr = [ 0 , 1 , 2 , 4 , 5].
  • hour = 3: eat fruit at index = 2 , so after an hour arr = [ 0 , 1 , 0 , 4 , 5].
  • hour = 4: eat fruit at index = 1 , so after an hour arr = [ 0 , 0 , 0 , 4 , 5].
  • hour = 5: eat fruit at index = 4 , so after an hour arr = [ 0 , 0, 0 , 4 , 2].
  • hour = 6: eat fruit at index = 3 , so after an hour arr = [ 0 , 0 , 0, 1, 2 ].
  • hour = 7: eat fruit at index = 4 , so after an hour arr = [ 0 , 0 , 0 , 1 , 0].
  • hour = 8: eat fruit at index = 3 , so after an hour arr = [ 0 , 0 , 0 , 0, 0].

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:

  • find out high limit: We know in the worst case H will be equal to N and in this case we have only one hour to eat ith kind of fruit so our answer will [ be in this case ] maximum element of ‘arr’ .
  • find out low limit: In best case it might happen we do not have any fruit then our low limit will be ‘0’ .

Monotonic Relation:

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

  • If T< H: then we can even find the lesser value of x which will also hold the condition .
  • Else: we have to increase the value of x because current value of x is insufficient.

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:

  • Apply Binary Search on X [answer].
  • Initialize low value = 0 and high = maximum element in arr.
  • Take X = ( low+high )/2;
  • For every value of X traverse whole array and find out the time required to eat all the fruits
  • If req_time < H: Then store the value of X and reduce our search space by making high = X-1;
  • Else: increase the value of low .

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
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}`);
Python3
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

Output
Minimum value of X will be : 7

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

Keywords to find out Binary Search Question:

  • The constraint on the array size is within a reasonable range, it is often less than or equal to 105.
  • The problem states a monotonic behaviour , where the target value can be achieved based on some specific condition.
  • The problem requires finding the minimum of maximums, maximum of minimums.

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




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads