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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read