![]() |
VOOZH | about |
Given a positive integer n, print all n-bit binary numbers having more 1’s than 0’s for any prefix of the number.
Examples:
Input : n = 2 Output : 11 10 Input : n = 4 Output : 1111 1110 1101 1100 1011 1010
A simple but not efficient solution will be to generate all N-bit binary numbers and print those numbers that satisfy the conditions. The time complexity of this solution is exponential.
An efficient solution is to generate only those N-bit numbers that satisfy the given conditions. We use recursion, At each point in the recursion, we append 0 and 1 to the partially formed number and recur with one less digit.
Implementation:
1111 1110 1101 1100 1011 1010
Time Complexity: O(n)
Auxiliary Space: O(n)
A non-recursive solution also exists, the idea is to directly generate the numbers in the range of 2N to 2(N-1) then require, only these which satisfies the condition:
Implementation:
1111 1110 1101 1100 1011 1010
Time Complexity: O(m*n)
Auxiliary Space: O(n)