N bit binary numbers
Learn how to solve the 'N bit binary numbers' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function n_bit_binary(n) that generates all n-bit binary numbers (as strings) such that in every prefix of the binary string, the number of 1s is greater than or equal to the number of 0s. Return the result as a sorted list of strings in lexicographic order.
- •1 <= n <= 15
Examples
n = 3
['110', '111']
For '110': prefixes '1'(1>=0✓), '11'(2>=0✓), '110'(2>=1✓). For '111': all prefixes have more 1s. '100','101','010' etc. fail the prefix condition.
n = 2
['10', '11']
'10': prefix '1' has 1>=0✓, '10' has 1>=1✓. '11': both prefixes valid. '00','01' fail.
n = 1
['1']
Only '1' satisfies the condition. '0' has prefix '0' with 0 ones and 1 zero.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.