Python BasicsEasy

N bit binary numbers

Detailed guide and Python implementation for the 'N bit binary numbers' problem.

Problem Statement

Easy

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.

Constraints
  • 1 <= n <= 15

Examples

Example 1
Input
n = 3
Output
['110', '111']
Explanation

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.

Example 2
Input
n = 2
Output
['10', '11']
Explanation

'10': prefix '1' has 1>=0✓, '10' has 1>=1✓. '11': both prefixes valid. '00','01' fail.

Example 3
Input
n = 1
Output
['1']
Explanation

Only '1' satisfies the condition. '0' has prefix '0' with 0 ones and 1 zero.

Need a Hint?
Consider using Recursion-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.