Given a positive integer n, find all n–digit binary numbers having more 1's than 0's for any prefix of the number.

For example, for n = 1, the binary numbers that satisfy the given constraints are 1111, 1110, 1101, 1100, 1011, 1010. Note that 1001 will not form part of the solution as it violates the problem constraints (1001 has 2 zeros and 1 one at third position). The same applies to all other 4–digit binary numbers.

Practice this problem

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

 
A better solution is to recursively generate only those n–digit numbers that satisfy the given constraints. The idea is to append 0 and 1 to the partially formed number and recur with one less digit at each point in the recursion. We also maintain a count of the total number of zeros and the number of ones in the partially formed number. Here, the optimization is to return if the total number of ones is less than the total number of zeros at any point in the recursion.

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

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
1111
1110
1101
1100
1011
1010

As mentioned by Matt in the comments below, we can improve the above code by excluding the possibility of making an invalid number. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
1111
1110
1101
1100
1011
1010