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):
- 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 high 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);
}
}
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
OutputValue 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
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}`);
OutputMinimum 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
|
|
---|
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem