We are given an integer N. We need to count the total number of such binary strings of length N such that the number of ‘0’s in the first string of length N/2 is double of the number of ‘0’s in the second string of length N/2.
Note: N is always an even positive integer.
Input : N = 4
Output : 2
Explanation: 0010 and 0001 are two binary string such that the number of zero in the first half is double the number of zero in second half.
Input : N = 6
Output : 9
Naive Approach:We can generate all the binary string of length N and then one by one can check that whether selected string follows the given scenario. But the time complexity for this approach is exponential and is O(N*2N).
Efficient Approach: This approach is based on some mathematical analysis of the problem.
Pre-requisite for this approach: Factorial and Combinatoric with modulo function.
Note: Let n = N/2.
If we perform some analysis step by step:
- The number of strings which contain two ‘0’ in first half string and one ‘0’ in second half string, is equal to nC2 * nC1.
- The number of strings which contain four ‘0’ in first half string and two ‘0’ in second half string, is equal to nC4 * nC2.
- The number of strings which contain six ‘0’ in first half string and three ‘0’ in second half string, is equal to nC6 * nC3.
We repeat above procedure till the number of ‘0’ in first half become n if n is even or (n-1) if n is odd.
So, our final answer is Σ (nC(2*i) * nCi), for 2 <= 2*i <= n.
Now, we can compute the required number of strings just by using Permutation and Combination.
int n = N/2; for(int i=2;i<=n;i=i+2) ans += ( nCr(n, i) * nCr(n, i/2);
Note : You can use Dynamic Programming technique to pre-compute CoeFunc(N, i) i.e. nCi.
Time complexity is O(N) if we pre-compute CoeFunc(N, i) in O(N*N).
- Count number of binary strings without consecutive 1's
- Count binary strings with k times appearing adjacent two set bits
- Count Pairs Of Consecutive Zeros
- Maximum difference of zeros and ones in binary string
- Maximum consecutive one’s (or zeros) in a binary array
- Maximum difference of zeros and ones in binary string | Set 2 (O(n) time)
- Find all even length binary sequences with same sum of first and second half bits
- Add n binary strings
- Count strings with consecutive 1's
- Program to add two binary strings
- Count common subsequence in two strings
- Count All Palindrome Sub-Strings in a String | Set 1
- Count of strings that can be formed using a, b and c under given constraints
- Count All Palindrome Sub-Strings in a String | Set 2
- Generate all binary strings without consecutive 1's
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.