# Generate all the binary strings of N bits

Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.
Examples:

`Input: 2Output:0 00 11 01 1Input: 3Output:0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1`

Approach: The idea is to try every permutation. For every position, there are 2 options, either ‘0’ or ‘1’. Backtracking is used in this approach to try every possibility/permutation.
Below is the implementation of the above approach:

## C++

 `// C++ implementation of the above approach:` `#include ``using` `namespace` `std;` `// Function to print the output``void` `printTheArray(``int` `arr[], ``int` `n)``{``    ``for` `(``int` `i = 0; i < n; i++) {``        ``cout << arr[i] << ``" "``;``    ``}``    ``cout << endl;``}` `// Function to generate all binary strings``void` `generateAllBinaryStrings(``int` `n, ``int` `arr[], ``int` `i)``{``    ``if` `(i == n) {``        ``printTheArray(arr, n);``        ``return``;``    ``}` `    ``// First assign "0" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = 0;``    ``generateAllBinaryStrings(n, arr, i + 1);` `    ``// And then assign "1" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = 1;``    ``generateAllBinaryStrings(n, arr, i + 1);``}` `// Driver Code``int` `main()``{``    ``int` `n = 4;` `    ``int` `arr[n];` `    ``// Print all binary strings``    ``generateAllBinaryStrings(n, arr, 0);` `    ``return` `0;``}`

## Java

 `// Java implementation of the above approach:``import` `java.util.*;` `class` `GFG``{` `// Function to print the output``static` `void` `printTheArray(``int` `arr[], ``int` `n)``{``    ``for` `(``int` `i = ``0``; i < n; i++) ``    ``{``        ``System.out.print(arr[i]+``" "``);``    ``}``    ``System.out.println();``}` `// Function to generate all binary strings``static` `void` `generateAllBinaryStrings(``int` `n, ``                            ``int` `arr[], ``int` `i)``{``    ``if` `(i == n) ``    ``{``        ``printTheArray(arr, n);``        ``return``;``    ``}` `    ``// First assign "0" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = ``0``;``    ``generateAllBinaryStrings(n, arr, i + ``1``);` `    ``// And then assign "1" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = ``1``;``    ``generateAllBinaryStrings(n, arr, i + ``1``);``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``int` `n = ``4``;` `    ``int``[] arr = ``new` `int``[n];` `    ``// Print all binary strings``    ``generateAllBinaryStrings(n, arr, ``0``);``}``}` `// This code is contributed by``// Surendra_Gangwar`

## Python3

 `# Python3 implementation of the ``# above approach ` `# Function to print the output ``def` `printTheArray(arr, n): ` `    ``for` `i ``in` `range``(``0``, n): ``        ``print``(arr[i], end ``=` `" "``) ``    ` `    ``print``()` `# Function to generate all binary strings ``def` `generateAllBinaryStrings(n, arr, i): ` `    ``if` `i ``=``=` `n:``        ``printTheArray(arr, n) ``        ``return``    ` `    ``# First assign "0" at ith position ``    ``# and try for all other permutations ``    ``# for remaining positions ``    ``arr[i] ``=` `0``    ``generateAllBinaryStrings(n, arr, i ``+` `1``) ` `    ``# And then assign "1" at ith position ``    ``# and try for all other permutations ``    ``# for remaining positions ``    ``arr[i] ``=` `1``    ``generateAllBinaryStrings(n, arr, i ``+` `1``) ` `# Driver Code ``if` `__name__ ``=``=` `"__main__"``: ` `    ``n ``=` `4``    ``arr ``=` `[``None``] ``*` `n ` `    ``# Print all binary strings ``    ``generateAllBinaryStrings(n, arr, ``0``) ` `# This code is contributed ``# by Rituraj Jain`

## C#

 `// C# implementation of the above approach:``using` `System;` `class` `GFG``{` `// Function to print the output``static` `void` `printTheArray(``int` `[]arr, ``int` `n)``{``    ``for` `(``int` `i = 0; i < n; i++) ``    ``{``        ``Console.Write(arr[i]+``" "``);``    ``}``    ``Console.WriteLine();``}` `// Function to generate all binary strings``static` `void` `generateAllBinaryStrings(``int` `n, ``                            ``int` `[]arr, ``int` `i)``{``    ``if` `(i == n) ``    ``{``        ``printTheArray(arr, n);``        ``return``;``    ``}` `    ``// First assign "0" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = 0;``    ``generateAllBinaryStrings(n, arr, i + 1);` `    ``// And then assign "1" at ith position``    ``// and try for all other permutations``    ``// for remaining positions``    ``arr[i] = 1;``    ``generateAllBinaryStrings(n, arr, i + 1);``}` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ``int` `n = 4;` `    ``int``[] arr = ``new` `int``[n];` `    ``// Print all binary strings``    ``generateAllBinaryStrings(n, arr, 0);``}``}` `// This code has been contributed by 29AjayKumar`

## Javascript

 ``

## PHP

 ``

Output
```0 0 0 0
0 0 0 1
0 0 1 0
0 0 1 1
0 1 0 0
0 1 0 1
0 1 1 0
0 1 1 1
1 0 0 0
1 0 0 1
1 0 1 0
1 0 1 1
1 1 0 0
1 1 0 1
1 1 1 0
1 1 1 1
```

Time complexity – O(2n)
Space complexity – O(n)

### Approach 2: Bit Manipulation

Step-by-step Explanation:

1. Generate all numbers from 0 to 2^n – 1.
2. Convert each number to its binary representation using the bitset class from the C++ Standard Library.
3. Extract the last n bits of the binary representation using the substr method.

## C++

 `#include ``#include ``using` `namespace` `std;` `int` `main() {``    ``int` `n = 4;``    ``for` `(``int` `i = 0; i < (1 << n); i++) {``        ``bitset<32> b(i);``        ``cout << b.to_string().substr(32-n) << endl;``    ``}``    ``return` `0;``}`

## Java

 `public` `class` `Main {` `    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `n = ``4``;``        ``// Loop over all possible combinations of n bits``        ``// using bit manipulation``        ``for` `(``int` `i = ``0``; i < (``1` `<< n); i++) {``            ``// Convert the integer 'i' to a binary string``            ``// representation of length 32 using the BitSet``            ``// class Note: Java's BitSet class does not have``            ``// a direct to_string() method like C++, so``            ``// we'll convert it to a binary string``            ``// representation using a custom method``            ``String binaryString = toBinaryString(i, n);``            ``System.out.println(binaryString);``        ``}``    ``}` `    ``// Custom method to convert an integer 'num' to a binary``    ``// string representation of length 'length'``    ``static` `String toBinaryString(``int` `num, ``int` `length)``    ``{``        ``StringBuilder sb = ``new` `StringBuilder();``        ``// Loop to append the binary digits to the``        ``// StringBuilder``        ``for` `(``int` `i = length - ``1``; i >= ``0``; i--) {``            ``// Use bitwise AND operation to extract the``            ``// binary digit at position 'i'``            ``int` `bit = (num & (``1` `<< i)) >> i;``            ``// Append the binary digit to the StringBuilder``            ``sb.append(bit);``        ``}``        ``return` `sb.toString();``    ``}``}`

## Python

 `def` `print_binary_combinations(n):``    ``# Loop through all numbers from 0 to 2^n - 1``    ``for` `i ``in` `range``(``1` `<< n):``        ``# Convert the current number to a binary string of length n``        ``binary_str ``=` `format``(i, ``'0'` `+` `str``(n) ``+` `'b'``)``        ``print``(binary_str)`  `# Example usage``n ``=` `4``print_binary_combinations(n)``#user_dtewbxkn77n`

## C#

 `using` `System;` `class` `GFG {``    ``static` `void` `Main()``    ``{``        ``int` `n = 4;``        ``for` `(``int` `i = 0; i < (1 << n); i++) {``            ``string` `binary``                ``= Convert.ToString(i, 2).PadLeft(n, ``'0'``);``            ``Console.WriteLine(binary);``        ``}``    ``}``}`

## Javascript

 ``

Output
```0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111
```

Time Complexity: O(n * 2^n)
Auxiliary Space: O(n)

Explanation:

The time complexity is O(n * 2^n) because we need to generate all 2^n binary strings and each binary string has a length of n. The auxiliary space complexity is O(n) because we need to store the binary representation of each number.

How is this approach different from another approach?

This approach is different from the recursive approach because it uses bit manipulation to generate all binary strings instead of recursion. The recursive approach has a time complexity of O(2^n) and an auxiliary space complexity of O(n), while this approach has a time complexity of O(n * 2^n) and an auxiliary space complexity of O(n).

Related Article: Generate all the binary number from 0 to n

Previous
Next