VOOZH about

URL: https://www.geeksforgeeks.org/dsa/generate-all-the-binary-strings-of-n-bits/

⇱ Generate all the binary strings of n bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generate all the binary strings of n bits

Last Updated : 29 Sep, 2025

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.

[Approach 1] Recursion with Backtracking

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.


Output
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.

[Approach 2] Using Bit Manipulation

We can think of every binary string of length n as just the binary representation of a number between 0 and 2n - 1.

  • For example, if n = 3, the numbers 0 to 7 in binary are:
    000, 001, 010, 011, 100, 101, 110, 111.

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.


Output
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


Comment
Article Tags:
Article Tags: