Given an integer, K. Generate all binary strings of size k without consecutive 1’s.
Examples:
Input : K = 3
Output : 000 , 001 , 010 , 100 , 101
Input : K = 4
Output :0000 0001 0010 0100 0101 1000 1001 1010
Idea behind that is IF string ends with ‘1’ then we put only ‘0’ at the end. IF string ends with ‘0’ then we put both ‘0’ and ‘1’ at the end of string for generating new string.
Below is algorithm
K : size of string
First We Generate All string starts with '0'
initialize n = 1 .
GenerateALLString ( K , Str , n )
a. IF n == K
PRINT str.
b. IF previous character is '1' :: str[n-1] == '1'
put str[n] = '0'
GenerateAllString ( K , str , n+1 )
c. IF previous character is '0' :: str[n-1] == '0'
First We Put zero at end and call function
PUT str[n] = '0'
GenerateAllString ( K , str , n+1 )
PUT str[n] = '1'
GenerateAllString ( K , str , n+1 )
Second Generate all binary string starts with '1'
DO THE SAME PROCESS
Below is the recursive implementation:
C++
#include<bits/stdc++.h>
using namespace std ;
void generateAllStringsUtil( int K, char str[], int n)
{
if (n == K)
{
str[n] = '\0' ;
cout << str << " " ;
return ;
}
if (str[n-1] == '1' )
{
str[n] = '0' ;
generateAllStringsUtil (K , str , n+1);
}
if (str[n-1] == '0' )
{
str[n] = '0' ;
generateAllStringsUtil(K, str, n+1);
str[n] = '1' ;
generateAllStringsUtil(K, str, n+1) ;
}
}
void generateAllStrings( int K )
{
if (K <= 0)
return ;
char str[K];
str[0] = '0' ;
generateAllStringsUtil ( K , str , 1 ) ;
str[0] = '1' ;
generateAllStringsUtil ( K , str , 1 );
}
int main()
{
int K = 3;
generateAllStrings (K) ;
return 0;
}
|
Java
import java.util.*;
import java.lang.*;
public class BinaryS {
public static String toString( char [] a) {
String string = new String(a);
return string;
}
static void generate( int k, char [] ch, int n) {
if (n == k) {
System.out.print(toString(ch)+ " " );
return ;
}
if (ch[n - 1 ] == '0' ) {
ch[n] = '0' ;
generate(k, ch, n + 1 );
ch[n] = '1' ;
generate(k, ch, n + 1 );
}
if (ch[n - 1 ] == '1' ) {
ch[n] = '0' ;
generate(k, ch, n + 1 );
}
}
static void fun( int k) {
if (k <= 0 ) {
return ;
}
char [] ch = new char [k];
ch[ 0 ] = '0' ;
generate(k, ch, 1 );
ch[ 0 ] = '1' ;
generate(k, ch, 1 );
}
public static void main(String args[]) {
int k = 3 ;
fun(k);
}
}
|
Python3
def generateAllStringsUtil(K, str , n):
if (n = = K):
print ( * str [:n], sep = " ", end = " ")
return
if ( str [n - 1 ] = = '1' ):
str [n] = '0'
generateAllStringsUtil (K, str , n + 1 )
if ( str [n - 1 ] = = '0' ):
str [n] = '0'
generateAllStringsUtil(K, str , n + 1 )
str [n] = '1'
generateAllStringsUtil(K, str , n + 1 )
def generateAllStrings(K):
if (K < = 0 ):
return
str = [ 0 ] * K
str [ 0 ] = '0'
generateAllStringsUtil (K, str , 1 )
str [ 0 ] = '1'
generateAllStringsUtil (K, str , 1 )
K = 3
generateAllStrings (K)
|
C#
using System;
class GFG {
static string toString( char [] a) {
string String = new string (a);
return String;
}
static void generate( int k, char [] ch, int n) {
if (n == k) {
Console.Write(toString(ch)+ " " );
return ;
}
if (ch[n - 1] == '0' ) {
ch[n] = '0' ;
generate(k, ch, n + 1);
ch[n] = '1' ;
generate(k, ch, n + 1);
}
if (ch[n - 1] == '1' ) {
ch[n] = '0' ;
generate(k, ch, n + 1);
}
}
static void fun( int k)
{
if (k <= 0)
{
return ;
}
char [] ch = new char [k];
ch[0] = '0' ;
generate(k, ch, 1);
ch[0] = '1' ;
generate(k, ch, 1);
}
static void Main()
{
int k = 3;
fun(k);
}
}
|
Javascript
<script>
function generateAllStringsUtil(K, str, n)
{
if (n == K)
{
str[n] = '\0' ;
document.write(str.join( "" ) + " " );
return ;
}
if (str[n-1] == '1' )
{
str[n] = '0' ;
generateAllStringsUtil (K , str , n+1);
}
if (str[n-1] == '0' )
{
str[n] = '0' ;
generateAllStringsUtil(K, str, n+1);
str[n] = '1' ;
generateAllStringsUtil(K, str, n+1) ;
}
}
function generateAllStrings(K )
{
if (K <= 0)
return ;
var str = new Array(K);
str[0] = '0 ' ;
generateAllStringsUtil ( K , str , 1 ) ;
// Generate all Binary string
// starts with ' 1 '
str[0] = ' 1' ;
generateAllStringsUtil ( K , str , 1 );
}
var K = 3;
generateAllStrings(K);
</script>
|
PHP
<?php
function generateAllStringsUtil( $K , & $str , $n ) {
if ( $n == $K ) {
echo implode( "" , array_slice ( $str , 0, $n )) . " " ;
return ;
}
if ( $str [ $n -1] == '1' ) {
$str [ $n ] = '0' ;
generateAllStringsUtil( $K , $str , $n + 1);
}
if ( $str [ $n -1] == '0' ) {
$str [ $n ] = '0' ;
generateAllStringsUtil( $K , $str , $n + 1);
$str [ $n ] = '1' ;
generateAllStringsUtil( $K , $str , $n + 1);
}
}
function generateAllStrings( $K ) {
if ( $K <= 0) {
return ;
}
$str = array_fill (0, $K , 0);
$str [0] = '0' ;
generateAllStringsUtil( $K , $str , 1);
$str [0] = '1' ;
generateAllStringsUtil( $K , $str , 1);
}
$K = 3;
generateAllStrings( $K );
?>
|
Output
000 001 010 100 101
Time complexity: O(2^K) where K is the size of the binary string. This is due to the fact that the algorithm recursively generates all possible binary strings of length K.
Auxiliary space: O(K), since we are using a string array of size K to store the binary string.
This problem is solved by using a recursion tree having two possibilities 0 or 1 just like selecting elements in a subsequence.
So we can also implement above approach using boolean array as well.
C++14
#include <bits/stdc++.h>
using namespace std;
void All_Binary_Strings( bool arr[], int num, int r)
{
if (r==num)
{
for ( int i=0;i<num;i++)
cout<<arr[i];
cout<< " " ;
return ;
}
else if (arr[r-1])
{
arr[r]=0;
All_Binary_Strings(arr,num,r+1);
}
else
{
arr[r]=0;
All_Binary_Strings(arr,num,r+1);
arr[r]=1;
All_Binary_Strings(arr,num,r+1);
}
}
void print( bool a[], int & num)
{
a[0]=0;
All_Binary_Strings(a,num,1);
a[0]=1;
All_Binary_Strings(a,num,1);
}
int main()
{
int n=2;
bool a[n];
print(a,n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void All_Binary_Strings( int arr[], int num, int r)
{
if (r == num)
{
for ( int i = 0 ; i < num; i++)
System.out.print(arr[i]);
System.out.print( " " );
return ;
}
else if (arr[r- 1 ] == 1 )
{
arr[r] = 0 ;
All_Binary_Strings(arr,num,r+ 1 );
}
else
{
arr[r] = 0 ;
All_Binary_Strings(arr,num,r+ 1 );
arr[r] = 1 ;
All_Binary_Strings(arr,num,r+ 1 );
}
}
static void print( int a[], int num)
{
a[ 0 ] = 0 ;
All_Binary_Strings(a,num, 1 );
a[ 0 ] = 1 ;
All_Binary_Strings(a,num, 1 );
}
public static void main(String args[])
{
int n = 2 ;
int a[] = new int [n];
print(a,n);
}
}
|
Python3
def All_Binary_Strings(arr,num,r):
if (r = = num):
for i in range (num):
print (arr[i],end = "")
print (end = " " )
return
elif (arr[r - 1 ]):
arr[r] = 0
All_Binary_Strings(arr, num, r + 1 )
else :
arr[r] = 0
All_Binary_Strings(arr,num,r + 1 )
arr[r] = 1
All_Binary_Strings(arr,num,r + 1 )
def Print (a,num):
a[ 0 ] = 0
All_Binary_Strings(a,num, 1 )
a[ 0 ] = 1
All_Binary_Strings(a,num, 1 )
n = 2
a = [ False for i in range (n)]
Print (a,n)
|
C#
using System;
public static class GFG {
public static void All_Binary_Strings( int [] arr,
int num, int r)
{
if (r == num) {
for ( int i = 0; i < num; i++) {
Console.Write(arr[i]);
}
Console.Write( " " );
return ;
}
else if (arr[r - 1] == 1) {
arr[r] = 0;
All_Binary_Strings(arr, num, r + 1);
}
else {
arr[r] = 0;
All_Binary_Strings(arr, num, r + 1);
arr[r] = 1;
All_Binary_Strings(arr, num, r + 1);
}
}
public static void print( int [] a, ref int num)
{
a[0] = 0;
All_Binary_Strings(a, num, 1);
a[0] = 1;
All_Binary_Strings(a, num, 1);
}
public static void Main()
{
int n = 2;
int [] a = new int [n];
print(a, ref n);
}
}
|
Javascript
<script>
function All_Binary_Strings(arr,num,r)
{
if (r == num)
{
for (let i = 0; i < num; i++)
document.write(arr[i]);
document.write( " " );
return ;
}
else if (arr[r-1])
{
arr[r] = 0;
All_Binary_Strings(arr, num, r + 1);
}
else
{
arr[r] = 0;
All_Binary_Strings(arr,num,r+1);
arr[r] = 1;
All_Binary_Strings(arr,num,r+1);
}
}
function print(a,num)
{
a[0] = 0;
All_Binary_Strings(a,num,1);
a[0] = 1;
All_Binary_Strings(a,num,1);
}
let n=2;
let a = new Array(n).fill( false );
print(a,n);
</script>
|
PHP
<?php
function allBinaryStrings( $arr , $num , $r ) {
if ( $r == $num ) {
for ( $i = 0; $i < $num ; $i ++) {
echo $arr [ $i ];
}
echo " " ;
return ;
} else if ( $arr [ $r -1] == 1) {
$arr [ $r ] = 0;
allBinaryStrings( $arr , $num , $r +1);
} else {
$arr [ $r ] = 0;
allBinaryStrings( $arr , $num , $r +1);
$arr [ $r ] = 1;
allBinaryStrings( $arr , $num , $r +1);
}
}
function printBinaryStrings( $num ) {
$arr = array_fill (0, $num , 0);
$arr [0] = 0;
allBinaryStrings( $arr , $num , 1);
$arr [0] = 1;
allBinaryStrings( $arr , $num , 1);
}
$n = 2;
printBinaryStrings( $n );
?>
|
Time Complexity: O(2^n),as we can see that we are calling the recursive function two times for every recursion level. Hence, the time complexity is 2^n.
Space Complexity: O(n) since we are using a boolean array of size n.
The above approach can also be solved using string. It does not have any effect on complexity but string handling, printing and operating is easy.
C++14
#include <bits/stdc++.h>
using namespace std;
void All_Binary_Strings(string str, int num)
{
int len=str.length();
if (len==num)
{
cout<<str<< " " ;
return ;
}
else if (str[len-1]== '1' )
All_Binary_Strings(str+ '0' ,num);
else
{
All_Binary_Strings(str+ '0' ,num);
All_Binary_Strings(str+ '1' ,num);
}
}
void print( int & num)
{
string word;
word.push_back( '0' );
All_Binary_Strings(word,num);
word[0]= '1' ;
All_Binary_Strings(word,num);
}
int main()
{
int n=4;
print(n);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static void All_Binary_Strings(String str, int num)
{
int len = str.length();
if (len == num) {
System.out.print(str + " " );
return ;
}
else if (str.charAt(len - 1 ) == '1' )
All_Binary_Strings(str + '0' , num);
else {
All_Binary_Strings(str + '0' , num);
All_Binary_Strings(str + '1' , num);
}
}
static void print( int num)
{
String word = "" ;
word += '0' ;
All_Binary_Strings(word, num);
word = "1" ;
All_Binary_Strings(word, num);
}
public static void main(String[] args)
{
int n = 4 ;
print(n);
}
}
|
Python3
def All_Binary_Strings( str ,num):
Len = len ( str )
if ( Len = = num):
print ( str ,end = " " )
return
elif ( str [ Len - 1 ] = = '1' ):
All_Binary_Strings( str + '0' ,num)
else :
All_Binary_Strings( str + '0' ,num)
All_Binary_Strings( str + '1' ,num)
def Print (num):
word = ""
word + = '0'
All_Binary_Strings(word,num)
word = '1'
All_Binary_Strings(word,num)
n = 4
Print (n)
|
C#
using System;
using System.Collections;
using System.Collections.Generic;
public class GFG {
static void All_Binary_Strings(String str, int num)
{
int len = str.Length;
if (len == num) {
Console.Write(str + " " );
return ;
}
else if (str[len - 1] == '1' )
All_Binary_Strings(str + '0' , num);
else {
All_Binary_Strings(str + '0' , num);
All_Binary_Strings(str + '1' , num);
}
}
static void print( int num)
{
string word = "" ;
word += '0' ;
All_Binary_Strings(word, num);
word = "1" ;
All_Binary_Strings(word, num);
}
public static void Main( string [] args)
{
int n = 4;
print(n);
}
}
|
Javascript
<script>
function All_Binary_Strings(str,num)
{
let len = str.length;
if (len == num)
{
document.write(str, " " );
return ;
}
else if (str[len - 1]== '1' )
All_Binary_Strings(str+ '0' ,num);
else
{
All_Binary_Strings(str+ '0' ,num);
All_Binary_Strings(str+ '1' ,num);
}
}
function print(num)
{
let word = "" ;
word += '0' ;
All_Binary_Strings(word,num);
word = '1' ;
All_Binary_Strings(word,num);
}
let n = 4;
print(n);
</script>
|
PHP
<?php
function allBinaryStrings( $str , $num ) {
$len = strlen ( $str );
if ( $len == $num ) {
echo $str . " " ;
return ;
} elseif ( $str [ $len - 1] == '1' ) {
allBinaryStrings( $str . '0' , $num );
} else {
allBinaryStrings( $str . '0' , $num );
allBinaryStrings( $str . '1' , $num );
}
}
function printBinaryStrings( $num ) {
$word = '0' ;
allBinaryStrings( $word , $num );
$word = '1' ;
allBinaryStrings( $word , $num );
}
$n = 4;
printBinaryStrings( $n );
?>
|
Output
0000 0001 0010 0100 0101 1000 1001 1010
Time Complexity: O(2^n)
Auxiliary Space: O(n)
Another easy recursion method to Generate Binary Strings Without Consecutive 1’s.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<string> generate_binary_strings( int n) {
if (n == 0) {
return { "" };
}
if (n == 1) {
return { "0" , "1" };
}
vector<string> result;
for (string s : generate_binary_strings(n - 1)) {
result.push_back(s + "0" );
if (s[s.length() - 1] != '1' ) {
result.push_back(s + "1" );
}
}
return result;
}
int main() {
vector<string> binary_strings = generate_binary_strings(4);
for (string s : binary_strings) {
cout << s << " " ;
}
return 0;
}
|
Java
import java.util.ArrayList;
public class Main {
public static ArrayList<String> generateBinaryStrings( int n) {
if (n == 0 ) {
ArrayList<String> emptyList = new ArrayList<String>();
emptyList.add( "" );
return emptyList;
}
if (n == 1 ) {
ArrayList<String> list = new ArrayList<String>();
list.add( "0" );
list.add( "1" );
return list;
}
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> prevList = generateBinaryStrings(n - 1 );
for (String s : prevList) {
result.add(s + "0" );
if (s.charAt(s.length() - 1 ) != '1' ) {
result.add(s + "1" );
}
}
return result;
}
public static void main(String[] args) {
ArrayList<String> binaryStrings = generateBinaryStrings( 4 );
for (String s : binaryStrings) {
System.out.print(s + " " );
}
}
}
|
Python3
def generate_binary_strings(n: int ):
if n = = 0 :
return [""]
if n = = 1 :
return [ "0" , "1" ]
result = []
for s in generate_binary_strings(n - 1 ):
result.append(s + "0" )
if s[ - 1 ] ! = "1" :
result.append(s + "1" )
return result
arr = generate_binary_strings( 4 )
for i in arr:
print (i,end = ' ' )
|
C#
using System;
using System.Collections.Generic;
public class Gfg
{
static List< string > GenerateBinaryStrings( int n)
{
if (n == 0)
{
return new List< string >() { "" };
}
if (n == 1)
{
return new List< string >() { "0" , "1" };
}
var result = new List< string >();
foreach ( string s in GenerateBinaryStrings(n - 1))
{
result.Add(s + "0" );
if (s[s.Length - 1] != '1' )
{
result.Add(s + "1" );
}
}
return result;
}
static void Main( string [] args)
{
List< string > binaryStrings = GenerateBinaryStrings(4);
foreach ( string s in binaryStrings)
{
Console.Write(s + " " );
}
Console.ReadLine();
}
}
|
Javascript
function generate_binary_strings(n) {
if (n == 0) {
return [ "" ];
}
if (n == 1) {
return [ "0" , "1" ];
}
let result = [];
var temp = generate_binary_strings(n - 1);
for (let i = 0; i < temp.length;i++) {
let s = temp[i];
result.push(s + "0" );
if (s[s.length - 1] != '1' ) {
result.push(s + "1" );
}
}
return result;
}
let binary_strings = generate_binary_strings(4);
for (let i = 0;i<binary_strings.length;i++)
console.log(binary_strings[i]+ " " );
|
PHP
<?php
function generateBinaryStrings( $n ) {
if ( $n == 0) {
return [ "" ];
}
if ( $n == 1) {
return [ "0" , "1" ];
}
$result = [];
$subStrings = generateBinaryStrings( $n - 1);
foreach ( $subStrings as $s ) {
$result [] = $s . "0" ;
if ( $s [ strlen ( $s ) - 1] != "1" ) {
$result [] = $s . "1" ;
}
}
return $result ;
}
$arr = generateBinaryStrings(4);
foreach ( $arr as $i ) {
echo $i . ' ' ;
}
?>
|
Output
0000 0001 0010 0100 0101 1000 1001 1010
Time Complexity: O(2n), where n is the length of the binary strings to be generated.
Auxiliary Space: O(2n) because at any point in time, the function stores all the binary strings generated so far in the result list, and as the number of strings generated is 2n, the space required to store them is also 2n.
If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
08 Dec, 2023
Like Article
Save Article