Count binary Strings that does not contain given String as Subsequence
Last Updated :
30 Mar, 2023
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);
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)
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));
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:
Similar Reads
Count of strings that does not contain any character of a given string
Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Count the strings that are subsequence of the given string
Given a string S and an array arr[] of words, the task is to return the number of words from the array which is a subsequence of S. Examples: Input: S = âprogrammingâ, arr[] = {"prom", "amin", "proj"}Output: 2Explanation: "prom" and "amin" are subsequence of S while "proj" is not) Input: S = âgeeksf
11 min read
Count of Subsequences of given string X in between strings Y and Z
Given three strings, 'X', 'Y' and 'Z', the task is to count the number of subsequences of 'X' which is lexicographically greater than or equal to 'Y' and lexicographically lesser than or equal to 'Z'. Examples: Input: X = "abc", Y = "a", Z = "bc"Output: 6Explanation: The subsequences of X which are
15+ min read
Count of substrings in a Binary String that contains more 1s than 0s
Given a binary string s, the task is to calculate the number of such substrings where the count of 1's is strictly greater than the count of 0's. Examples Input: S = "110011"Output: 11Explanation: Substrings in which the count of 1's is strictly greater than the count of 0's are { S[0]}, {S[0], S[1]
15+ min read
Count subsequences 01 in string generated by concatenation of given numeric string K times
Given a string S and a positive integer K, the task is to find the number of subsequences "01" in the string generated by concatenation of the given numeric string S K times. Examples: Input: S = "0171", K = 2Output: 6Explanation:The string formed by concatenation of S, K number of times is "0171017
6 min read
Count of strings that does not contain Arc intersection
Given an array arr[] consisting of N binary strings, the task is to count the number of strings that does not contain any Arc Intersection. Connecting consecutive pairs of identical letters using Arcs, if there is an intersection obtained, then it is known as Arc Intersection. Below is the illustrat
8 min read
Count of sub-strings that do not consist of the given character
Given a string str and a character c. The task is to find the number of sub-strings that do not consist of the character c. Examples: Input: str = "baa", c = 'b' Output: 3 The sub-strings are "a", "a" and "aa" Input: str = "ababaa", C = 'b' Output: 5 Approach: Initially take a counter that counts th
12 min read
Count of substrings that start and end with 1 in given Binary String
Given a binary string, count the number of substrings that start and end with 1. Examples: Input: "00100101"Output: 3Explanation: three substrings are "1001", "100101" and "101" Input: "1001"Output: 1Explanation: one substring "1001" Recommended PracticeCount SubstringsTry It!Count of substrings tha
12 min read
Count ways to generate Binary String not containing "0100" Substring
Given the number N, count the number of ways to create a binary string (the string that contains characters as zero or one) of size N such that it does not contain "0100" as a substring. A substring is a contiguous sequence of characters within a string. Examples: Input: N = 4Output: 15Explanation:
15+ min read
Count subsequences in first string which are anagrams of the second string
Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count all the subsequences of str1 which are anagrams of str2. Examples: Input : str1 = "abacd", str2 = "abc" Output : 2 Index of characters in the 2 subsequences are: {0, 1, 3} = {a, b, c} = abc and {1, 2, 3} = {b,
13 min read