


bool isBadVersion(version) returns true for all versions ‘V’ such that V > X, where X is the first bad version.
The first line of input contains an integer ‘T’ denoting the number of test cases.
Then the T test cases follow.
The first and only input line will have two space-separated integers N(total number of versions) and V(the first bad version).
For each test case, print a single line containing a single integer denoting the first bad version.
The output of each test case will be printed in a separate line.
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= V <= N
1 <= N <= 100000
Where ‘T’ is the number of test cases, ‘N’ is the total number of versions we have, and ‘V’ is the version.
Time limit: 1 sec.
The brute force approach that you might think of is to use the linear search algorithm. Checking for each version ‘V’ starting from 1 to N until you find the first bad version. That is for all versions V such that 1<= V <= N, find the value of isBadVersion and return V such that isBadVersion(V) = false and isBadVersion(V+1) = true.
The better approach would be to use a binary search.
Initialise “low” and “high” to 0 and ‘N’ - 1, respectively.
Assign (“low” + (“high” - “low”) / 2 ) to “mid”.
Let us see the different cases:
See the following case:
N = 9, R = 4
Mid => 5
But, the first bad version starts from 4 which is not equal to 5.
Hence, we can say that mid may or may not be the first bad version, but we can tell for sure that all values of V greater than mid can be discarded. Hence we now set high as mid and check in the interval [low, mid].