![]() |
VOOZH | about |
Given a positive integer number n. Generate all the binary strings of n bits.
A binary string is a string consisting only of the characters '0' and '1'.
Examples:
Input: n = 2
Output: [00, 01, 10, 11]
Explanation: We have to print all binary numbers of length 2. As each position can be either 0 or 1, the total possible combinations are 4.Input: n = 3
Output: [000, 001, 010, 011, 100, 101, 110, 111]
Explanation: We have to print all binary numbers of length 3. As each position can be either 0 or 1, the total possible combinations are 8.
To generate all binary strings of length n, we use recursion with backtracking. At each position, we have two choices: place 0 or place 1. The function explores both choices recursively until the full string of length n is formed. Once a string is complete, it is printed, and then the function backtracks to try the other option. This ensures that all 2n binary strings are generated.
000 001 010 011 100 101 110 111
Time Complexity: O(n * 2n), because we need to generate all 2n binary strings and each binary string has a length of n.
Auxiliary Space: O(n), due to recursion stack and storing binary representation of each number.
We can think of every binary string of length n as just the binary representation of a number between 0 and 2n - 1.
So, by iterating through all numbers in this range and converting each number to its n-bit binary form, we automatically generate all possible binary strings.
000 001 010 011 100 101 110 111
Time Complexity: O(n * 2n), because we need to generate all 2n binary strings and each binary string has a length of n.
Auxiliary Space: O(n), because we need to store the binary representation of each number.
Related Article: Generate all the binary number from 0 to n