You have been given an integer 'N'. Your task is to generate and return all binary strings of length 'N' such that there are no consecutive 1's in the string.
A binary string is that string which contains only ‘0’ and ‘1’.
Let ‘N'=3, hence the length of the binary string would be 3.
We can have the following binary strings with no consecutive 1s:
000 001 010 100 101
The first line contains a single integer 'N' denoting the length of the binary string to be generated.
Output Format
All possible binary strings without consecutive ‘1’ of the length 'N' will be printed in lexicographically increasing order.
Note:
You don't need to print anything; it has already been taken care of. Just implement the given function.
4
0000 0001 0010 0100 0101 1000 1001 1010
For N = 4 we get the following Strings:
0000 0001 0010 0100 0101 1000 1001 1010
Note that none of the strings has consecutive 1s. Also, note that they are in a lexicographically increasing order.
2
00 01 10
1 <= 'N' <= 20
Time limit: 1 second
Recursively generate all possible strings that satisfy the condition
Since we need to generate all substrings which does not have consecutive 1s we can simply start adding new characters to the string until the length of the string is ‘K’ taking care that if the last character of the current string is ‘1’ we cannot add another ‘1’ as it will result in consecutive ‘1s.’ Otherwise, if the last character is ‘0’ we have 2 options either to add ‘1’ or ‘0’. We explore both the options recursively until we have a string of desired length i.e ‘K’ .
Our recursive function works as follows:
O(2 ^ N), ‘N’ is the length of the string.
For every character, we have 2 choices either put a ‘0’ or a ‘1’ hence for ‘N’ choices we will have a total time complexity of order of O(2 ^ N)
O(N), ‘N’ is the length of the string
The recursive stack uses space of the order O(N).