Open In App

Count binary Strings that does not contain given String as Subsequence

Improve
Improve
Like Article
Like
Save
Share
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




// Java code to implement the approach
import java.io.*;
 
class GFG{
 
// Returns the number of strings that does
// not contain S as its subsequence.
static 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
static void countBinStrings(int N, String S)
{
 
    // Size of the string
    int sizeOfString = S.length();
 
    System.out.println(recur(0, 0, sizeOfString, N));
}
 
// Driver Code
public static void main (String[] args)
{
    int N = 3;
    String S = "10";
 
    // Function Call
    countBinStrings(N, S);
 
    int N1 = 5;
    String S1 = "1010";
    // Function Call
    countBinStrings(N1, S1);
}
}
 
// This code is contributed by Pushpesh Raj.


Python3




# Python code for the above approach
def count_bin_strings(N, S):
   
    # Size of the string
    size_of_string = len(S)
 
    def recur(i, cur_match):
        # If curMatch is S then here after
        # strings will contain string S as
        # subsequence so return 0.
        if cur_match == size_of_string:
            return 0
 
        # Base Case
        if i == N:
            return 1
 
        # Calling both Match and NoMatch
        ans = recur(i + 1, cur_match + 1) + recur(i + 1, cur_match)
 
        # Returning answer
        return ans
 
    print(recur(0, 0))
 
# Driver Code
if __name__ == '__main__':
    N = 3
    S = "10"
 
    # Function Call
    count_bin_strings(N, S)
 
    N1 = 5
    S1 = "1010"
     
    # Function Call
    count_bin_strings(N1, S1)
     
# This code is contributed by Potta Lokesh


C#




// C# code to implement the approach
 
using System;
 
public class GFG {
 
// Returns the number of strings that does
// not contain S as its subsequence.
static 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
static void countBinStrings(int N, string S)
{
 
    // Size of the string
    int sizeOfString = S.Length;
 
    Console.WriteLine(recur(0, 0, sizeOfString, N));
}
     
// Driver code
public static void Main(string[] args)
{
    int N = 3;
    string S = "10";
 
    // Function Call
    countBinStrings(N, S);
 
    int N1 = 5;
    string S1 = "1010";
    // Function Call
    countBinStrings(N1, S1);
}
}


Javascript




// Javascript code to implement the approach
 
// Returns the number of strings that does
// not contain S as its subsequence.
function recur(i, curMatch, S, 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
    let 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
function countBinStrings(N, S)
{
 
    // Size of the string
    let sizeOfString = S.length;
 
    document.write(recur(0, 0, sizeOfString, N));
}
 
// Driver Code
    let N = 3;
    let S = "10";
 
    // Function Call
    countBinStrings(N, S);
     
    document.write("<br>");
     
    let N1 = 5;
    let S1 = "1010";
    // Function Call
    countBinStrings(N1, S1);


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




import java.util.Arrays;
 
public class Main {
 
    // dp table initialized with - 1
    static int[][] dp = new int[100001][5];
 
    // Returns number of strings that does
    // not contain S in its subsequence.
    static 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
    static void countBinStrings(int N, String S)
    {
 
        // dp table initialized with -1
        for (int[] row : dp)
            Arrays.fill(row, -1);
 
        // Size of the string
        int sizeOfString = S.length();
 
        System.out.println(recur(0, 0, sizeOfString, N));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 3;
        String S = "10";
 
        // Function Call
        countBinStrings(N, S);
 
        int N1 = 5;
        String S1 = "1010";
 
        // Function Call
        countBinStrings(N1, S1);
    }
}
 
// This code is contributed by surajrasr7277


Python3




# Python code to implement the approach
 
# dp table initialized with - 1
dp = [[-1]*5 for _ in range(100001)];
 
# Returns number of strings that does
# not contain S in its subsequence.
def recur(i, curMatch, S, 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
    ans = recur(i + 1, curMatch + 1, S, N) + recur(i + 1, curMatch, S, N);
 
    # Saving and returning the answer
    dp[i][curMatch]=ans;
    return dp[i][curMatch];
 
# Function to count number of binary
# strings that does not contain S
# as its subsequence
def countBinStrings( N,  S):
 
    # dp table initialized with -1
    for i in range(0,100001):
        for j in range(0,5):
            dp[i][j]=-1;
 
    # Size of the string
    sizeOfString = len(S);
 
    print(recur(0, 0, sizeOfString, N));
 
# Driver Code
N = 3;
S = "10";
 
# Function Call
countBinStrings(N, S);
 
N1 = 5;
S1 = "1010";
 
# Function Call
countBinStrings(N1, S1);


C#




// C# code to implement the approach
 
using System;
using System.Linq;
using System.Collections.Generic;
 
class GFG {
 
    // dp table initialized with - 1
    static int[,] dp=new int[100001, 5];
     
    // Returns number of strings that does
    // not contain S in its subsequence.
    static 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
    static void countBinStrings(int N, string S)
    {
     
        // dp table initialized with -1
        for(int i=0; i<100001; i++)
            for(int j=0; j<5; j++)
                dp[i,j]=-1;
        // Size of the string
        int sizeOfString = S.Length;
     
        Console.WriteLine(recur(0, 0, sizeOfString, N));
    }
     
    // Driver Code
    public static void Main (string[] args)
    {
        int N = 3;
        string S = "10";
     
        // Function Call
        countBinStrings(N, S);
     
        int N1 = 5;
        string S1 = "1010";
     
        // Function Call
        countBinStrings(N1, S1);
    
}


Javascript




// Javascript code to implement the approach
// dp table initialized with -1
let dp = [];
for(let i = 0; i<100001; i++){
    dp[i] = new Array(5);
}
 
// returns number of strings that does
// not contain S in its subsequence.
function recur(i, curMatch, S, 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
    let 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
function countBinStrings(N, S){
    // dp table initialized with -1
    for(let i = 0; i<100001; i++){
        for(let j = 0; j<5; j++){
            dp[i][j] = -1;
        }
    }
     
    // size of the string
    let sizeOfString = S.length;
     
    console.log(recur(0,0,sizeOfString, N));
}
 
// driver code
let N = 3;
let S = "10";
 
// function call
countBinStrings(N, S);
 
let N1 = 5;
let S1 = "1010";
 
// function call
countBinStrings(N1, S1);
 
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)


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




import java.util.*;
 
class Main {
    // Returns number of strings that does
    // not contain S in its subsequence.
    static int countBinStrings(int N, int S)
    {
        int dp[][] = new int[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
    public static void main(String[] args)
    {
        int N = 3;
        String S = "10";
        System.out.println(countBinStrings(N, S.length()));
 
        int N1 = 5;
        String S1 = "1010";
        int s = S1.length();
        System.out.println(countBinStrings(N1, s));
    }
}


Python3




# Python3 code for the above approach
 
# Returns number of strings that does
# not contain S in its subsequence.
def countBinStrings(N, S):
    dp = [[0 for j in range(S+1)] for i in range(N+1)]
 
    # Initializing dp table
    for i in range(N+1):
        for j in range(S+1):
            if j == S:
                dp[i][j] = 0
            elif i == N:
                dp[i][j] = 1
 
    # Filling the dp table
    for i in range(N-1, -1, -1):
        for j in range(S-1, -1, -1):
            dp[i][j] = dp[i+1][j+1] + dp[i+1][j]
 
    # Returning the answer
    return dp[0][0]
 
# Driver Code
if __name__ == "__main__":
    N = 3
    S = "10"
    print(countBinStrings(N, len(S)))
 
    N1 = 5
    S1 = "1010"
    s = len(S1)
    print(countBinStrings(N1, s))


C#




// C# code for the above approach
using System;
 
public class Program {
  public static int CountBinStrings(int N, int S)
  {
    int[, ] dp = new int[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];
  }
 
  public static void Main()
  {
    int N = 3;
    string S = "10";
    Console.WriteLine(CountBinStrings(N, S.Length));
 
    int N1 = 5;
    string S1 = "1010";
    int s = S1.Length;
    Console.WriteLine(CountBinStrings(N1, s));
  }
}
 
// this code is contributed by chetanbargal


Javascript




// Javascript code for the above approach
 
// Returns number of strings that does
// not contain S in its subsequence.
function countBinStrings(N, S) {
  let dp = new Array(N + 1);
  for (let i = 0; i <= N; i++) {
    dp[i] = new Array(S + 1);
    for (let 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 (let i = N - 1; i >= 0; i--) {
    for (let 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
let N = 3;
let S = "10";
console.log(countBinStrings(N, S.length));
 
let N1 = 5;
let S1 = "1010";
let s = S1.length;
console.log(countBinStrings(N1, s));


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:



Last Updated : 30 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads