Given a value X, the task is to find a minimum size binary string, such that if any 2 characters are deleted at random, the probability that both the characters will be ‘1’ is 1/X. Print the size of such binary string.
Example:
Input:_ X = 2_
Output:_ 4_
Explanation:
Let the binary string be “0111”.
Probability of choosing 2 1s from given string is = 3C2 / 4C2 = 3/6 = 1/2 (which is equal to 1/X).
Hence the required size is 4.
(Any 4 size binary string with 3 ‘1’s and 1 ‘0’ can be taken for this example).
Input:_ X = 8_
Output:_ 5_
Approach: We will try to find a formula to solve this problem.
Let
r = Number of 1’s in the string
and
b = Number of 0’s in the string.
Total number of ways = (r + b) C 2.
Below is the implementation of the above approach.
// C++ implementation of the
// above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
// Function returns the minimum
// size of the string
**int**
MinimumString(``**int**
x)
{
// From formula
**int**
b = 1;
// Left limit of r
**double**
left_lim =
**sqrt**``(x) + 1.0;
// Right limit of r
**double**
right_lim =
**sqrt**``(x) + 2.0;
**int**
r;
**for**
(``**int**
i = left_lim; i <= right_lim; i++) {
**if**
(i > left_lim and i < right_lim) {
// Smallest integer in
// the valid range
r = i;
**break**``;
}
}
**return**
b + r;
}
// Driver Code
**int**
main()
{
**int**
X = 2;
cout << MinimumString(X);
**return**
0;
}
Output:
4
Time Complexity: O(1), as the difference between left_lim and right_lim will be always less than 1.
Auxiliary Space: O(1)
#combinatorial #competitive programming #mathematical #binary-string #probability #arrays