Given an integer N, the task is to generate all possible binary strings of length N which contain “01” as the sub-string exactly twice.
Input: N = 4
“0101” is the only binary string of length 4
that contains “01” exactly twice as the sub-string.
Input: N = 5
Approach: This problem can solved using backtracking. To generate a binary string, we implement a function that generate each bit at a time, update the state of the binary string (current length, number of occurrences of the pattern). Then call the function recursively, and according to the current state of the binary string, the function will decide how to generate the next bit or print out the binary string (if the problem’s requirement is met).
For this problem, backtracking strategy looks like we generate a binary tree with each node can have either value 0 or 1.
For example, with N = 4, the tree will look like:
Below is the implementation of the above approach:
00101 01001 01010 01011 01101 10101
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.