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.

Try It Yourself
redirect icon

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

C++
#include <iostream>
#include <vector>
using namespace std;

// recursive function to generate all binary strings
void binstrRec(string &s, int i, vector<string> &res) {
    int n = s.size();

    // if string is complete, add to result
    if (i == n) {
        res.push_back(s);
        return;
    }

    // assign '0' at current position
    s[i] = '0';
    binstrRec(s, i + 1, res);

    // assign '1' at current position
    s[i] = '1';
    binstrRec(s, i + 1, res);
}

// function to return all binary strings of length n
vector<string> binstr(int n) {
    string s(n, '0');
    
    vector<string> res;
    
    binstrRec(s, 0, res);
    
    return res;
}

int main() {
    int n = 3;

    vector<string> ans = binstr(n);

    for (auto &x : ans) cout << x << " ";

    return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

class GFG {

    // recursive function to generate all binary strings
    static void binstrRec(char[] s, int i, ArrayList<String> res) {
        int n = s.length;

        // if string is complete, add to result
        if (i == n) {
            res.add(new String(s));
            return;
        }

        // assign '0' at current position
        s[i] = '0';
        binstrRec(s, i + 1, res);

        // assign '1' at current position
        s[i] = '1';
        binstrRec(s, i + 1, res);
    }
    
    // function to return all binary strings of length n
    static ArrayList<String> binstr(int n) {
        char[] s = new char[n];

        Arrays.fill(s, '0');

        ArrayList<String> res = new ArrayList<>();

        binstrRec(s, 0, res);

        return res;
    }

    public static void main(String[] args) {
        int n = 3;

        List<String> ans = binstr(n);

        for (String x : ans) System.out.print(x + " ");
    }
}
Python
# recursive function to generate all binary strings
def binstrRec(s, i, res):
    n = len(s)

    # if string is complete, add to result
    if i == n:
        res.append("".join(s))
        return

    # assign '0' at current position
    s[i] = '0'
    binstrRec(s, i + 1, res)

    # assign '1' at current position
    s[i] = '1'
    binstrRec(s, i + 1, res)

# function to return all binary strings of length n
def binstr(n):
    s = ['0'] * n
    res = []
    binstrRec(s, 0, res)
    return res

if __name__ == "__main__":
    n = 3

    ans = binstr(n)

    for x in ans:
        print(x, end=" ")
C#
using System;
using System.Collections.Generic;

class GFG {

    // recursive function to generate all binary strings
    static void binstrRec(char[] s, int i, List<string> res) {
        int n = s.Length;

        // if string is complete, add to result
        if (i == n) {
            res.Add(new string(s));
            return;
        }

        // assign '0' at current position
        s[i] = '0';
        binstrRec(s, i + 1, res);

        // assign '1' at current position
        s[i] = '1';
        binstrRec(s, i + 1, res);
    }
    
    // function to return all binary strings of length n
    static List<string> binstr(int n) {
        char[] s = new string('0', n).ToCharArray();
        
        List<string> res = new List<string>();
        
        binstrRec(s, 0, res);
        return res;
    }

    static void Main() {
        int n = 3;

        List<string> ans = binstr(n);

        foreach (string x in ans) Console.Write(x + " ");
    }
}
JavaScript
// recursive function to generate all binary strings
function binstrRec(s, i, res) {
    let n = s.length;

    // if string is complete, add to result
    if (i === n) {
        res.push(s.join(""));
        return;
    }

    // assign '0' at current position
    s[i] = '0';
    binstrRec(s, i + 1, res);

    // assign '1' at current position
    s[i] = '1';
    binstrRec(s, i + 1, res);
}

// function to return all binary strings of length n
function binstr(n) {
    let s = new Array(n).fill('0');
    let res = [];
    binstrRec(s, 0, res);
    return res;
}

// Driver Code
let n = 3;
let ans = binstr(n);

console.log(ans.join(" "));

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.

C++
#include <iostream>
#include <vector>
using namespace std;

vector<string> binstr(int n) {
    vector<string> res;

    for (int i = 0; i < (1 << n); i++) {
        string s;

        // build string from bits of i
        for (int j = n - 1; j >= 0; --j)
            s += ((i >> j) & 1) ? '1' : '0';

        res.push_back(s);
    }
    
    return res;
}

int main() {
    int n = 3;
    vector<string> ans = binstr(n);

    for (auto &s : ans) cout << s << " ";
}
Java
import java.util.List;
import java.util.ArrayList;

class GFG {

    static ArrayList<String> binstr(int n) {
        ArrayList<String> res = new ArrayList<>();
        
        for (int i = 0; i < (1 << n); i++) {
            
            StringBuilder s = new StringBuilder();
            
            // build string from bits of i
            for (int j = n - 1; j >= 0; j--)
                s.append(((i >> j) & 1) == 1 ? '1' : '0');
            
            res.add(s.toString());
        }
        
        return res;
    }

    public static void main(String[] args) {
        int n = 3;
        ArrayList<String> ans = binstr(n);

        for (String s : ans) System.out.print(s + " ");
    }
}
Python
def binstr(n):
    res = []
    for i in range(1 << n):
        
        # build string from bits of i
        s = ''.join('1' if (i >> j) & 1 else '0' for j in reversed(range(n)))
        res.append(s)
        
    return res

if __name__ == "__main__":
    n = 3
    ans = binstr(n)

    print(" ".join(ans))
C#
using System;
using System.Collections.Generic;

class GFG {

    static List<string> binstr(int n) {
        List<string> res = new List<string>();

        for (int i = 0; i < (1 << n); i++) {
            char[] s = new char[n];

            // build string from bits of i
            for (int j = n - 1; j >= 0; j--) {
                s[n - 1 - j] = ((i >> j) & 1) == 1 ? '1' : '0';
            }

            res.Add(new string(s));
        }
        
        return res;
    }

    static void Main() {
        int n = 3;
        List<string> ans = binstr(n);

        foreach (string s in ans) Console.Write(s + " ");
    }
}
JavaScript
function binstr(n) {
    let res = [];
 
    for (let i = 0; i < (1 << n); i++) {
        let s = '';

        // build string from bits of i
        for (let j = n - 1; j >= 0; j--)
            s += ((i >> j) & 1) ? '1' : '0';
        res.push(s);
    }
    return res;
}

// Driver Code
let n = 3;
let ans = binstr(n);

console.log(ans.join(" "));

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