Generate all the binary strings of N bits.

Generate all the binary strings of N bits. 


Given a positive integer number N. Generate all the binary strings(0 and 1) of N bits. 

Case 1
 Input: length=2
 Output:
 0 0
 0 1
 1 0
 1 1

Case 2
 Input: length=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

Case 3
 Input: length=1
 Output:
 0
 1

Algorithm:


We will see two approach of generating the binary string combination. 

First approach, where we will form the binary string one by one and once it matches the required length, we will backtrack and switch the binary digit. In this approach, as String is immutable each character we append to a String will create new String object.

Recursive stack trace of Generating all the binary strings of N bits.
generate all binary strings of length n with k bits set
Generate all the binary strings of N bits.

Second approach, In the first approach, each time we append the new character to String, a new String literal is created, so why to waste the space. In this approach we will use the fixed size array so that anytime we iterate and use the array we will always be working on fixed size array.

for more details on String and Memory management in Java, visit Java Memory Management Interview Questions

Java Program to Generate all the binary strings of N bits.


package javabypatel;
 
public class GenerateBinaryString {
 
    public void printBinaryCombination(int length, String str) {
        if (str.length() == length) {
            System.out.println(str);
            return;
        }
        printBinaryCombination(length, str + "0");
        printBinaryCombination(length, str + "1");
    }
 
    public static void main(String[] args) {
        GenerateBinaryString obj = new GenerateBinaryString();
        int length = 3;

        System.out.println("Approach 1");
        obj.printBinaryCombination(length, "");
    }
}

Optimized Approach: Using Array so no new String is created when a character is appended each time


package javabypatel;
 
import java.util.Arrays;
 
public class GenerateBinaryString {
 
    public void printBinaryCombination(int index, int[] arr) {
        if (index == arr.length) {
            System.out.println(Arrays.toString(arr));
            return;
        }
        arr[index] = 0;
        printBinaryCombination(index + 1, arr);
        arr[index] = 1;
        printBinaryCombination(index + 1, arr);
    }
 
    public static void main(String[] args) {
        GenerateBinaryString obj = new GenerateBinaryString();
        int length = 3;
 
        System.out.println("Approach 2");
        obj.printBinaryCombination(0, new int[length]);
    }
}

You may also like to see


Write a program to print all permutations of a given string without repetition. (Repetition of characters is not allowed).

Write a program to print all permutations of a given string with repetition. (Repetition of characters is allowed).

Print all subsets of a given set.

Enjoy !!!! 

If you find any issue in post or face any error while implementing, Please comment.

Check if an array is sorted in Java - Iterative and Recursive approach

Check if an array is sorted in Java - Iterative and Recursive approach.


Given an array, check if it is already sorted or not using both Iterative and Recursive way.

Lets see sample input and output for better understanding:
Check whether the array is sorted in Java
Check whether array is sorted or not

Reverse a Number in Java.

Reverse a Number in Java.


Given a integer number, reverse it.

Lets see sample input and output for better understanding:
Reverse a number in Java input output example
Reverse a number in Java input output example

Find length of the longest valid parenthesis substring

Find length of the longest balanced parenthesis in a string.


Given a string consisting of opening and closing parenthesis, find the length of the longest balanced parenthesis in it.

Lets see sample input and output for better understanding:
count longest valid parentheses length
longest valid parentheses count

Sort a Stack using Merge Sort

Sort a Stack using Merge Sort.


Lets see how to sort a stack using merge sort which uses divide and conquer recursive algorithm.

I recommend reading Merge sort first before proceeding.
Also, check Merge sort article on linked list that will help in understanding Merge sort and this article better.

Lets see sample input and output for better understanding:
sort a stack using recursion in java
Sort a Stack using Merge Sort in Java

Print path from root to a given node in a binary tree

Print path from root to a given node in a binary tree.


Given a Binary tree and a Key, Print a path from root to a key node.
Note: Given tree is Binary Tree and not Binary Search Tree.

Lets see sample input and output for better understanding:
Print path from root to given node in binary tree
Print path from root to given node in binary tree

Simple Deadlock Program in Java

Simple java program to create Deadlock.


Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.


Let's consider an example, in the office we have shared Printer and Scanner where Employees has ability to do scanning and printing.

1. John has bunch of documents that it wants to Print first and also want to take a Scan later.
(Print and Scan)

2. Michael has bunch of documents that it wants to Scan first and also want to take a Print later.
(Scan and Print)

Difference between process and thread

Difference between process and thread.


Point 1:
A process is an executing instance of an application.
Thread is independent path of execution within a process. Process can have multiple threads,

Point 2:
Threads itself is capable enough to do all the things a process does and thread is a part of process that is why thread can be termed as light-weight process.

Point 3:
Since all the Threads are part of a same Process they all share same memory allocated by Process.
Process use memory allocated by OS.

Point 4:
Inter-thread communication between threads is easy whereas Inter-process communication is difficult.

Point 5:
Processes have independent data and code segments.
Thread shares the data segment, code segment, files etc. with its peer threads.

Point 6:
Process switching is complex as compared to thread switching because of the amount of variables need to be maintained in both of the case.

Per process items Per thread items
Address space  Program counter
Global variables Registers
Open files Stack
Child processes State
Pending alarms
Signals and signal handlers
Accounting information

Delete Middle Node of Linked List in Java

Delete Middle Node of Linked List in Java.


Given a linked list, Delete the middle node of linked list.

Lets see sample input and output for better understanding:

Remove duplicates from an unsorted linked list in Java.

Remove duplicates from an unsorted linked list in Java..


Given an unsorted linked list, Remove duplicates from it.

Lets see sample input and output for better understanding: