Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Recursion & Backtracking

All Binary Strings of Length N

Easy · Recursion & Backtracking · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

Print every binary string of length n (made of 0 and 1) in increasing lexicographic order, one per line.

Input

A single integer n.

Output

2^n lines.

Constraints

Recursion: at each position try 0 first, then 1. When the string reaches length n, print it. Trying 0 first gives lexicographic order for free.

Example 1

Input

2

Output

00
01
10
11

Example 2

Input

3

Output

000
001
010
011
100
101
110
111

Hints

  1. Build the string one character at a time.
  2. At each position there are two choices: 0 or 1.
  3. Trying 0 before 1 prints the strings in lexicographic order.

Approach

A recursive function gen(cur) stops and records cur when it has length n; otherwise it calls gen(cur + "0") and then gen(cur + "1"). The recursion tree has 2^n leaves — one per string — and the left-before-right order is exactly the sorted order. Collect the output in one buffer, since it can be 4096 lines.

Complexity: O(n · 2^n) time · O(n) recursion depth

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int n;
string out;

void gen(string &cur) {
    if ((int) cur.size() == n) {
        out += cur + "\n";
        return;
    }
    for (char c : {'0', '1'}) {
        cur.push_back(c);
        gen(cur);
        cur.pop_back();
    }
}

int main() {
    cin >> n;
    string cur;
    gen(cur);
    cout << out;
    return 0;
}

Python solution

n = int(input())
out = []


def gen(cur):
    if len(cur) == n:
        out.append(cur)
        return
    gen(cur + "0")
    gen(cur + "1")


gen("")
print("\n".join(out))

Java solution

import java.util.*;

public class Main {
    static int n;
    static StringBuilder out = new StringBuilder();

    static void gen(StringBuilder cur) {
        if (cur.length() == n) {
            out.append(cur).append('\n');
            return;
        }
        for (char c : new char[] {'0', '1'}) {
            cur.append(c);
            gen(cur);
            cur.deleteCharAt(cur.length() - 1);
        }
    }

    public static void main(String[] args) {
        n = new Scanner(System.in).nextInt();
        gen(new StringBuilder());
        System.out.print(out);
    }
}

Solve All Binary Strings of Length N online · All practice problems