Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Hide Buttons

Generate All Strings of n bits.

Objec­tive: Generate All Strings of n bits, consider A[0..n-1] is an array of size n.

Example :

n = 3
Output:
[0, 0, 0]    [1, 0, 0]    [0, 1, 0]    [1, 1, 0]

[0, 0, 1]     [1, 0, 1]     [0, 1, 1]    [1, 1, 1]

Approach:

  • Recursion is key here.
  • create a integer array of size n.
  • Now if we think of every bit, it can take 2 values, 0 and 1.
  • starting from the end of the string, set the bit 0 and 1 and make recursive calls

Time Complexity – O(2^n)
Code:

Output:

[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: