Generate all the binary strings of N bits
Last Updated :
07 May, 2025
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: 2
Output:
0 0
0 1
1 0
1 1
Input: 3
Output:
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 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 <bits/stdc++.h>
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
Python
# 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
<script>
// Javascript implementation of the above approach:
// Function to print the output
function printTheArray(arr, n)
{
for (let i = 0; i < n; i++)
{
document.write(arr[i]+" ");
}
document.write("</br>");
}
// Function to generate all binary strings
function 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);
}
let n = 4;
let arr = new Array(n);
arr.fill(0);
// Print all binary strings
generateAllBinaryStrings(n, arr, 0);
// This code is contributed by divyeshrabadiya07.
</script>
PHP
<?php
// PHP implementation of the above approach
// Function to print the output
function printTheArray($arr, $n)
{
for ($i = 0; $i < $n; $i++)
{
echo $arr[$i], " ";
}
echo "\n";
}
// Function to generate all binary strings
function 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
$n = 4;
$arr = array_fill(0, $n, 0);
// Print all binary strings
generateAllBinaryStrings($n, $arr, 0);
// This code is contributed by Ryuga
?>
Output0 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:
- Generate all numbers from 0 to 2^n - 1.
- Convert each number to its binary representation using the bitset class from the C++ Standard Library.
- Extract the last n bits of the binary representation using the substr method.
C++
#include <iostream>
#include <bitset>
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
<script>
const n = 4;
for (let i = 0; i < (1 << n); i++) {
const binaryString = (i >>> 0).toString(2).padStart(n, '0');
console.log(binaryString);
}
</script>
Output0000
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
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
C++ Programming Language C++ is a computer programming language developed by Bjarne Stroustrup as an extension of the C language. It is known for is fast speed, low level memory management and is often taught as first programming language. It provides:Hands-on application of different programming concepts.Similar syntax to
5 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read