Count ways to generate Binary String not containing "0100" Substring
Last Updated :
22 Mar, 2023
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 = 4
Output: 15
Explanation: The answer will contain all possible substrings of size 4 except 0100 itself.
Input: N = 5
Output: 28
Naive approach: The article can be solved based on the following idea:
There are N positions to fill of binary string with either 1 or 0 while avoiding "0100" substring, for any position i recursive function will be called by setting that position with either 1 or 0 except when last three characters are 010 only recursive function is called for 1 (to form 0101) not for 0 since if 0 is called then 0100 will be present as a substring in given count of strings. Now to keep track of last three characters make use of bitmask.
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 the last three characters in form of a bitmask.
- Check the base cases. If the value of i is equal to N return 1.
- If the last three characters are not 010 Call the function recursively for 1 and 0, and sum up the values that are returned.
- else if the last three characters are 010 then call the function only for 1.
- return the value sum.
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Returns number of strings that does
// not contain 0100 in its substring
int recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
int ans = 0LL;
if (i >= 3 and lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
return ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
void countBinStrings(int N)
{
cout << recur(0, 0, N) << endl;
}
// Driver Code
int main()
{
int N = 4;
// Function Call
countBinStrings(N);
int N1 = 5;
// Function Call
countBinStrings(N1);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
static int recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
int ans = 0;
if (i >= 3 && lastThreeDigits == 2)
{
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1,
lastThreeDigits << 1 & 7 | 1, N);
// Choosing 0 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7,
N);
}
return ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
static void countBinStrings(int N)
{
System.out.println(recur(0, 0, N));
}
// Driver Code
public static void main(String[] args)
{
int N = 4;
// Function Call
countBinStrings(N);
int N1 = 5;
// Function Call
countBinStrings(N1);
}
}
// This code is contributed by lokesh.
Python3
#Python code for the above approach
def recur(i, lastThreeDigits, N):
# Base Case
if i == N:
return 1
ans = 0
if i >= 3 and lastThreeDigits == 2:
# If last three substring is 010
# then only one option we have to
# choose for next character which
# is 1 so lastThreeDigits will be
# 5 which is 101
ans += recur(i + 1, 5, N)
else:
# Choosing 1 as a next character by
# left shifting lastThreeDigits by
# 1 then taking its bitwise AND with
# 7 so that only first three bits
# remain active and others become zero
ans += recur(i + 1, (lastThreeDigits << 1) & 7 | 1, N)
# Choosing 0 as a next character by
# left shifting lastThreeDigits by
# 1 then taking its bitwise AND with
# 7 so that only first three bits
# remain active and others become zero
ans += recur(i + 1, (lastThreeDigits << 1) & 7, N)
return ans
# Function to count number of binary
# strings that does not contain 0100
# as substring
def countBinStrings(N):
print(recur(0, 0, N))
# Driver code
N = 4
# Function Call
countBinStrings(N)
N1 = 5
# Function Call
countBinStrings(N1)
#This code is contributed by Potta Lokesh
C#
// C# code to implement the approach
using System;
using System.Collections.Generic;
public class Gfg {
// Returns number of strings that does
// not contain 0100 in its substring
static int recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
int ans = 0;
if (i >= 3 && lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
return ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
static void countBinStrings(int N)
{
Console.WriteLine(recur(0, 0, N));
}
// Driver Code
public static void Main(string[] args)
{
int N = 4;
// Function Call
countBinStrings(N);
int N1 = 5;
// Function Call
countBinStrings(N1);
}
}
JavaScript
// Javascript code for the above approach
// Returns number of strings that does
// not contain 0100 in its substring
function recur(i, lastThreeDigits, N)
{
// Base Case
if (i == N)
return 1;
let ans = 0;
if (i >= 3 && lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character by
// left shifting lastThreeDigits by
// 1 then taking its bitwise AND with
// 7 so that only first three bits
// remain active and others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
return ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
function countBinStrings(N)
{
console.log(recur(0, 0, N));
}
// Driver Code
let N = 4;
// Function Call
countBinStrings(N);
let N1 = 5;
// Function Call
countBinStrings(N1);
// This code is contributed by poojaagarwal2.
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 * 8 states but the recursive function is called several 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 a HashMap and whenever the function is called, return the value store without computing .
Follow the steps below to solve the problem:
- Create a 2d array of dp[N + 1][8] initially filled with -1.
- If the answer for a particular state is computed then save it in dp[i][lastThreeDigits].
- If the answer for a particular state is already computed then just return dp[i][lastThreeDigits].
Below is the implementation of the above approach.
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
int dp[100001][8];
// Returns number of strings that does
// not contain 0100 in its substring
int recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
// If answer for current state is
// already calculated then just
// return the answer.
if (dp[i][lastThreeDigits] != -1)
return dp[i][lastThreeDigits];
int ans = 0LL;
if (i >= 3 and lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise
// AND with 7 so that only first
// three bits remain active and
// others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise AND
// with 7 so that only first three
// bits remain active and others
// become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
// Saving and returning sum
return dp[i][lastThreeDigits] = ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
void countBinStrings(int N)
{
// Initializing value of dp with -1
memset(dp, -1, sizeof(dp));
cout << recur(0, 0, N) << endl;
}
// Driver Code
int main()
{
int N = 4;
// Function Call
countBinStrings(N);
int N1 = 5;
// Function Call
countBinStrings(N1);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
class GFG {
static int[][] dp=new int[100001][8];
// Returns number of strings that does
// not contain 0100 in its substring
static int recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
// If answer for current state is
// already calculated then just
// return the answer.
if (dp[i][lastThreeDigits] != -1)
return dp[i][lastThreeDigits];
int ans = 0;
if (i >= 3 && lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise
// AND with 7 so that only first
// three bits remain active and
// others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise AND
// with 7 so that only first three
// bits remain active and others
// become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
// Saving and returning sum
return dp[i][lastThreeDigits] = ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
static void countBinStrings(int N)
{
// Initializing value of dp with -1
for(int i=0;i<dp.length;i++)
{
for(int j=0;j<dp[0].length;j++)
{
dp[i][j]=-1;
}
}
System.out.println(recur(0, 0, N));
}
// Driver Code
public static void main (String[] args)
{
int N = 4;
// Function Call
countBinStrings(N);
int N1 = 5;
// Function Call
countBinStrings(N1);
}
}
// This code is contributed by Aman Kumar
Python3
# Python code to implement the approach
# Returns number of strings that does
# not contain 0100 in its substring
def recur(i, lastThreeDigits, N, dp):
# Base Case
if i == N:
return 1
# If answer for current state is already
# calculated then just return the answer.
if dp[i][lastThreeDigits] != -1:
return dp[i][lastThreeDigits]
ans = 0
if i >= 3 and lastThreeDigits == 2:
# If last three substring is 010 then only one option
# we have to choose for next character which is 1 so
# lastThreeDigits will be 5 which is 101
ans += recur(i + 1, 5, N, dp)
else:
# Choosing 1 as a next character by left shifting
# lastThreeDigits by 1 then taking its bitwise AND
# with 7 so that only first three bits remain active
# and others become zero
ans += recur(i + 1, (lastThreeDigits << 1) & 7 | 1,
N, dp)
# Choosing 0 as a next character by left shifting
# lastThreeDigits by 1 then taking its bitwise AND
# with 7 so that only first three bits remain active
# and others become zero
ans += recur(i + 1, (lastThreeDigits << 1) & 7,
N, dp)
# Saving and returning sum
dp[i][lastThreeDigits] = ans
return ans
# Function to count number of binary strings that does
# not contain 0100 as substring
def countBinStrings(N):
# Initializing value of dp with -1
dp = [[-1 for j in range(8)] for i in range(100001)]
print(recur(0, 0, N, dp))
# Driver Code
if __name__ == "__main__":
N = 4
# Function Call
countBinStrings(N)
N1 = 5
# Function Call
countBinStrings(N1)
# This code is contributed by sankar.
C#
// C# code implementation for the above approach
using System;
public class GFG {
static int[, ] dp = new int[100001, 8];
// Returns number of strings that does not contain 0100
// in its substring
static int Recur(int i, int lastThreeDigits, int N)
{
// Base Case
if (i == N)
return 1;
// If answer for current state is already calculated
// then just return the answer.
if (dp[i, lastThreeDigits] != -1)
return dp[i, lastThreeDigits];
int ans = 0;
if (i >= 3 && lastThreeDigits == 2) {
// If last three substring is 010 then only one
// option we have to choose for next character
// which is 1 so lastThreeDigits will be 5 which
// is 101
ans += Recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character by left
// shifting lastThreeDigits by 1 then taking its
// bitwise AND with 7 so that only first three
// bits remain active and others become zero
ans += Recur(i + 1,
(lastThreeDigits << 1) & 7 | 1, N);
// Choosing 0 as a next character by left
// shifting lastThreeDigits by 1 then taking its
// bitwise AND with 7 so that only first three
// bits remain active and others become zero
ans += Recur(i + 1, (lastThreeDigits << 1) & 7,
N);
}
// Saving and returning sum
return dp[i, lastThreeDigits] = ans;
}
// Function to count number of binary strings that does
// not contain 0100 as substring
static void CountBinStrings(int N)
{
// Initializing value of dp with -1
for (int i = 0; i < dp.GetLength(0); i++) {
for (int j = 0; j < dp.GetLength(1); j++) {
dp[i, j] = -1;
}
}
Console.WriteLine(Recur(0, 0, N));
}
static public void Main()
{
// Code
int N = 4;
// Function Call
CountBinStrings(N);
int N1 = 5;
// Function Call
CountBinStrings(N1);
}
}
// This code is contributed by karthik.
JavaScript
// JS code to implement the approach
// dp table initialized with - 1
let dp=new Array(100001);
for(let i=0; i<100001; i++)
dp[i]=new Array(8);
// Returns number of strings that does
// not contain 0100 in its substring
function recur( i, lastThreeDigits, N)
{
// Base Case
if (i == N)
return 1;
// If answer for current state is
// already calculated then just
// return the answer.
if (dp[i][lastThreeDigits] != -1)
return dp[i][lastThreeDigits];
let ans = 0;
if (i >= 3 && lastThreeDigits == 2) {
// If last three substring is 010
// then only one option we have to
// choose for next character which
// is 1 so lastThreeDigits will be
// 5 which is 101
ans += recur(i + 1, 5, N);
}
else {
// Choosing 1 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise
// AND with 7 so that only first
// three bits remain active and
// others become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7 | 1,
N);
// Choosing 0 as a next character
// by left shifting lastThreeDigits
// by 1 then taking its bitwise AND
// with 7 so that only first three
// bits remain active and others
// become zero
ans += recur(i + 1, lastThreeDigits << 1 & 7, N);
}
// Saving and returning sum
return dp[i][lastThreeDigits] = ans;
}
// Function to count number of binary
// strings that does not contain 0100
// as substring
function countBinStrings( N)
{
// Initializing value of dp with -1
for(let i=0; i<100001; i++)
for(let j=0; j<8; j++)
dp[i][j]=-1;
console.log(recur(0, 0, N)+"<br>");
}
// Driver Code
let N = 4;
// Function Call
countBinStrings(N);
let N1 = 5;
// Function Call
countBinStrings(N1);
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles :
Similar Reads
Count of substrings of a Binary string containing only 1s
Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
6 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 N-length Binary Strings consisting of "11" as substring
Given a positive integer N, the task is to find the number of binary strings of length N which contains "11" as a substring. Examples: Input: N = 2Output: 1Explanation: The only string of length 2 that has "11" as a substring is "11". Input: N = 12Output: 3719 Approach: The idea is to derive the num
8 min read
Count of substrings of a binary string containing K ones
Given a binary string of length N and an integer K, we need to find out how many substrings of this string are exist which contains exactly K ones. Examples: Input : s = â10010â K = 1 Output : 9 The 9 substrings containing one 1 are, â1â, â10â, â100â, â001â, â01â, â1â, â10â, â0010â and â010âRecommen
7 min read
Count of K length subarrays containing only 1s in given Binary String
Given a binary string str, the task is to find the count of K length subarrays containing only 1s. Examples: Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays with 1 ones Input: str = "11111001", K=3Output: 3 Approach: The task can be solved by keeping track of the
4 min read
Count ways to partition a Binary String such that each substring contains exactly two 0s
Given binary string str, the task is to find the count of ways to partition the string such that each partitioned substring contains exactly two 0s. Examples: Input: str = "00100" Output: 2Explanation: Possible ways to partition the string such that each partition contains exactly two 0s are: { {"00
6 min read
Count of K length subarrays containing only 1s in given Binary String | Set 2
Given binary string str, the task is to find the count of K length subarrays containing only 1s. Examples Input: str = "0101000", K=1Output: 2Explanation: 0101000 -> There are 2 subarrays of length 1 containing only 1s. Input: str = "11111001", K=3Output: 3 Approach: The given problem can also be
4 min read
Count binary Strings that does not contain given String as Subsequence
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: 4Explanation: There are 8 strings possible to fill 3 positions with 0's or 1's. {"000",
15+ min read
Count of substrings from given Ternary strings containing characters at least once
Given string str of size N consisting of only 0, 1, and 2, the task is to find the number of substrings that consists of characters 0, 1, and 2 at least once. Examples: Input: str = "0122"Output: 2Explanation:There exists 2 substrings such that the substrings has characters 0, 1, 2 at least once is
6 min read
Counting even decimal value substrings in a binary string
Given a binary string of size N. Count all substring that have even decimal value considering binary to decimal conversion from left to right (For example a substring "1011" is treated as 13) Examples : Input : 101Output : 2Explanation : Substring are : 1, 10, 101, 0, 01, 1 In decimal form : 1, 1, 3
9 min read