Given a positive integer n, count all n–digit binary numbers without any consecutive 1's.

For example, for n = 5, the binary numbers that satisfy the given constraints are: [00000, 00001, 00010, 00100, 00101, 01000, 01001, 01010, 10000, 10001, 10010, 10100, 10101].

Practice this problem

 
A simple solution would be to generate all n–digit integers and print only those integers that satisfy the given constraints. The complexity of this solution would be exponential.

 
A better solution is to generate only those n–digit integers that satisfy the given constraints. The idea is to use recursion. We append 0 and 1 to the partially formed number and recur with one less digit at each point in the recursion. Here, the trick is to append 1 and recur only if the last digit of the partially formed number is 0. That way, we will never have any consecutive 1's in the output string.

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

Java


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

Python


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

The time complexity of the above solution is exponential and occupies space in the call stack.

 
The problem has an optimal substructure and exhibits overlapping subproblems. If we draw the solution’s recursion tree, we can see that the same subproblems are getting computed repeatedly. We know that problems with optimal substructure and overlapping subproblems can be solved using dynamic programming, in which subproblem solutions are memoized rather than computed repeatedly.

The algorithm can be implemented as follows in C++, Java, and Python, where we solve smaller subproblems first, then solve larger subproblems from them.

C++


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

Java


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

Python


Download  Run Code

Output:

The total number of 5–digit binary numbers without any consecutive 1’s is 13

The time complexity of the above solution is O(n) and requires O(n) extra space, where n is the total number of digits.

How to print all binary numbers?

The following recursive code in C++, Java, and Python prints all binary numbers as well:

C++


Download  Run Code

Output:

00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101

Java


Download  Run Code

Output:

00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101

Python


Download  Run Code

Output:

00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101