Count of binary string of length N with at least X 0s and Y 1s
Given three numbers N, X, and Y, find the count of unique binary strings of length N having at least X 0s and Y 1s.
Examples:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.
Input: N=5, X=1, Y=2
Output: 25Input: N=3, X=1, Y=1
Output: 6
Explanation: There are 3 binary strings of length 3 with at least 1 0s and 1 1s, such as: 001, 010, 100, 011, 101, 110
Naive approach: Generate all binary strings of length N and then count the number of strings with at least X 0s and Y 1s.
Time Complexity: O(2^N)
Auxiliary Space: O(1)
Better Approach: This problem can also be solved using Combinatorics. If the length is N, and given is X 0s, then there will be Y (=N-X) 1s. So we need to find the number of unique combinations for this, which can be obtained as (N)C(X) or (N)C(Y). Now for all unique binary strings, we need to find the nCi for values of i in the range [X, N-Y] and add it to a variable. The value of this sum after all iterations will be the required count.
Efficient Approach: The above approach can further be optimized with the help of the Pascal triangle to calculate nCr. Follow the steps below to solve the problem:
- Initialize the 2-D array p[][] to calculate using the pascal triangle.
- Initialize the variable sum as 0 to store the answer.
- Iterate over the range [x, n-y] using the variable i and perform the following tasks:
- Add the value p[n][i] to the variable sum.
- After performing the above steps, print the value of sum as the answer.
Below is the implementation of the above approach.
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; long long int p[31][31]; // Function to use pascal trianglevoid pascalTriangle(){ p[0][0] = 1; p[1][0] = 1; p[1][1] = 1; for (int i = 2; i < 31; i++) { p[i][0] = 1; for (int j = 1; j < i; j++) p[i][j] = p[i - 1][j] + p[i - 1][j - 1]; p[i][i] = 1; }} // Function to count the total number of wayslong long int countWays(int n, int x, int y){ // Store the answer long long int sum = 0; // Traverse for (long long int i = x; i <= n - y; i++) { sum += p[n][i]; } return sum;} // Driver Codeint main(){ pascalTriangle(); int N = 5, X = 1, Y = 2; cout << countWays(N, X, Y) << endl; return 0;} |
25
Time Complexity: O(N)
Auxiliary Space: O(1)


