Open In App

Count binary Strings that does not contain given String as Subsequence

Last Updated : 30 Mar, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given a number N and string S, count the number of ways to create a binary string (containing only ‘0’ and ‘1’) of size N such that it does not contain S as a subsequence.

Examples: 

Input: N = 3, S = “10”.
Output: 4
Explanation: There are 8 strings possible to fill 3 positions with 0’s or 1’s. {“000”, “001”, “010”, “100”, “”011”, “110”, “101”, “111”} and only {“000”, “001”, “011”, “111”} are valid strings that do not contain “10” as a subsequence. so the answer will be 4.

Input: N = 5, S = “1010”
Output: 26

Naive approach: The basic way to solve the problem is as follows:

The first thing to be observed is that answer does not depends upon the string S itself but only depends upon the size of  S. There are N positions to fill of binary string with either 1 or 0 avoiding S forming its subsequence.  There is a need to keep track of matches as well which stores how many characters of a given string S have been matched with a string that is being created. if it is equal to the size of S then return 0 since the strings will be invalid from there on. the recursive function will be called for each position ‘i’ as Match and No Match. 

Follow the steps below to solve the problem:

  • Create a recursive function that takes two parameters one is the position that needs to fill and the other is how many of the characters have been matched from string S.
  • Check if all characters are matched then return 0.
  • Check the base cases. If the value of i is equal to N return 1.
  • Call the recursive function for both Match and NoMatch and Sum up the values that are returned.
  • return the value sum.

Below is the code to implement the above approach :

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// Returns the number of strings that does
// not contain S as its subsequence.
int recur(int i, int curMatch, int S, int N)
{
 
    // If curMatch is S then here after
    // strings will contain string S as
    // subsequence so return 0.
    if (curMatch == S)
        return 0;
 
    // Base Case
    if (i == N)
        return 1;
 
    // Calling both Match and NoMatch
    int ans = recur(i + 1, curMatch + 1, S, N)
              + recur(i + 1, curMatch, S, N);
 
    // Returning answer
    return ans;
}
 
// Function to count number of binary
// strings that does not contain S
// as its subsequence
void countBinStrings(int N, string S)
{
 
    // Size of the string
    int sizeOfString = S.size();
 
    cout << recur(0, 0, sizeOfString, N) << endl;
}
 
// Driver Code
int main()
{
    int N = 3;
    string S = "10";
 
    // Function Call
    countBinStrings(N, S);
 
    int N1 = 5;
    string S1 = "1010";
    // Function Call
    countBinStrings(N1, S1);
    return 0;
}


Java

Python3

C#

Javascript

Output

4
26

Time Complexity: O(2n)
Auxiliary Space: O(1)

Efficient Approach:  The above approach can be optimized based on the following idea:

The idea is similar, but it can be observed that there are N * 5 states but the recursive function is called 2n times. That means that some states are called repeatedly. So the idea is to store the value of states. This can be done using recursive structure intact and just store the value in an array or HashMap and whenever the function is called, return the value store without computing .

dp[i][j] = X represents count of binary strings of size i and j matches has done from string S.

Follow the steps below to solve the problem:

  • Create a 2d array of dp[N + 1][5] initially filled with -1.
  • If the answer for a particular state is computed then save it in dp[i][curMatch].
  • If the answer for a particular state is already computed then just return dp[i][curMatch].

Below is the implementation of the above approach.

C++




// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
 
// dp table initialized with - 1
int dp[100001][5];
 
// Returns number of strings that does
// not contain S in its subsequence.
int recur(int i, int curMatch, int S, int N)
{
 
    // If curMatch is S then here after
    // strings will contain string S as
    // subsequence so return 0.
    if (curMatch == S)
        return 0;
 
    // Base Case
    if (i == N)
        return 1;
 
    // If the answer for current state
    // is already calculated then return
    // the precalculated answer
    if (dp[i][curMatch] != -1)
        return dp[i][curMatch];
 
    // Calling both Match and NoMatch
    int ans = recur(i + 1, curMatch + 1, S, N)
              + recur(i + 1, curMatch, S, N);
 
    // Saving and returning the answer
    return dp[i][curMatch] = ans;
}
 
// Function to count number of binary
// strings that does not contain S
// as its subsequence
void countBinStrings(int N, string S)
{
 
    // dp table initialized with -1
    memset(dp, -1, sizeof(dp));
 
    // Size of the string
    int sizeOfString = S.size();
 
    cout << recur(0, 0, sizeOfString, N) << endl;
}
 
// Driver Code
int main()
{
    int N = 3;
    string S = "10";
 
    // Function Call
    countBinStrings(N, S);
 
    int N1 = 5;
    string S1 = "1010";
 
    // Function Call
    countBinStrings(N1, S1);
    return 0;
}


Java

Python3

C#

Javascript

Output

4
26

Time Complexity: O(N)
Auxiliary Space: O(N)

Efficient approach : Using DP Tabulation method ( Iterative approach )

The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.

Steps to solve this problem :

  • Create a table to store the solution of the subproblems.
  • Initialize the table with base cases
  • Fill up the table iteratively
  • Return the final solution

Implementation :

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Returns number of strings that does
// not contain S in its subsequence.
int countBinStrings(int N, int S)
{
    int dp[N+1][S+1];
 
    // Initializing dp table
    for(int i=0; i<=N; i++){
        for(int j=0; j<=S; j++){
            if(j==S){
                dp[i][j] =0;
            }
            else if(i==N){
                dp[i][j] = 1;
            }
        }
    }
 
    // Filling the dp table
    for(int i=N-1; i>=0; i--){
        for(int j=S-1; j>=0; j--){
            dp[i][j]= dp[i+1][j+1] + dp[i+1][j];
        }
    }
 
    // Returning the answer
    return dp[0][0];
}
 
// Driver Code
int main()
{
    int N = 3;
    string S = "10";
    cout << countBinStrings(N, S.size()) << endl;
 
    int N1 = 5;
    string S1 = "1010";
    int s = S1.size();
    cout << countBinStrings(N1, s) << endl;
 
    return 0;
}
// this code is contributed by bhardwajji


Java

Python3

C#

Javascript

Output

4
26

Time Complexity: O(N * S), where S is the length of the string and N is mentioned in the problem statement
Auxiliary Space: O(N * S), where S is the length of the string and N is mentioned in the problem statement

Related Articles:



Next Article

Similar Reads