Back to Practice Dashboard
Python BasicsEasy

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

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?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
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.

Open in Editor