Generate all binary strings without consecutive 1's
Given an integer n, the task is to generate all binary strings of size n without consecutive 1's.
Examples:
Input : n = 4
Output : 0000 0001 0010 0100 0101 1000 1001 1010Input : n = 3
Output : 000 001 010 100 101
Approach:
The idea is to generate all binary strings of length n without consecutive 1's using a recursive backtracking approach that explores all valid configurations. We start with a string of all '0's and then recursively consider two options for each position: either keep it as '0' or change it to '1'. When we place a '1' at any position, we skip the next position in our recursive exploration to ensure we don't create consecutive 1's.
Step by step approach:
- Initialize a string of length n with all zeros.
- For each position, explore two possibilities: keeping '0' or placing '1'.
- When placing '1' at a position, skip the next position in recursion to avoid consecutive 1's.
- On reaching the end of the string, add the string to the resultant array.
- Use backtracking to restore the state and explore all possible paths.
// C++ program to Generate all binary
// strings without consecutive 1's
#include <bits/stdc++.h>
using namespace std;
// Recursive helper function to generate binary strings
void stringRecur(int i, string &s, vector<string> &ans) {
// Base case: If we've filled all positions,
// add the string to results
if (i >= s.length()) {
ans.push_back(s);
return;
}
// Case 1: Keep the current position as
// '0' and move to next position
stringRecur(i+1, s, ans);
// Case 2: Try placing '1' at current position.
// Skip the next position when we place a '1'
// to avoid consecutive 1's
s[i] = '1';
// Skip next position to avoid consecutive 1's
stringRecur(i+2, s, ans);
// Backtrack: Restore the current position back to '0'
s[i] = '0';
}
vector<string> generateBinaryStrings(int n) {
// Initialize a string of n zeros
// as our starting point
string s(n, '0');
vector<string> ans;
stringRecur(0, s, ans);
return ans;
}
int main() {
int n = 4;
vector<string> res = generateBinaryStrings(n);
for (auto s: res) {
cout << s << endl;
}
return 0;
}
// Java program to Generate all binary
// strings without consecutive 1's
import java.util.*;
class GfG {
// Recursive helper function to generate binary strings
static void stringRecur(int i, StringBuilder s, List<String> ans) {
// Base case: If we've filled all positions,
// add the string to results
if (i >= s.length()) {
ans.add(s.toString());
return;
}
// Case 1: Keep the current position as
// '0' and move to next position
stringRecur(i + 1, s, ans);
// Case 2: Try placing '1' at current position.
// Skip the next position when we place a '1'
// to avoid consecutive 1's
s.setCharAt(i, '1');
// Skip next position to avoid consecutive 1's
stringRecur(i + 2, s, ans);
// Backtrack: Restore the current position back to '0'
s.setCharAt(i, '0');
}
static List<String> generateBinaryStrings(int n) {
// Initialize a string of n zeros
// as our starting point
StringBuilder s = new StringBuilder();
for (int j = 0; j < n; j++) {
s.append('0');
}
List<String> ans = new ArrayList<>();
stringRecur(0, s, ans);
return ans;
}
public static void main(String[] args) {
int n = 4;
List<String> res = generateBinaryStrings(n);
for (String s : res) {
System.out.println(s);
}
}
}
# Python program to Generate all binary
# strings without consecutive 1's
# Recursive helper function to generate binary strings
def stringRecur(i, s, ans):
# Base case: If we've filled all positions,
# add the string to results
if i >= len(s):
ans.append(''.join(s))
return
# Case 1: Keep the current position as
# '0' and move to next position
stringRecur(i + 1, s, ans)
# Case 2: Try placing '1' at current position.
# Skip the next position when we place a '1'
# to avoid consecutive 1's
s[i] = '1'
# Skip next position to avoid consecutive 1's
stringRecur(i + 2, s, ans)
# Backtrack: Restore the current position back to '0'
s[i] = '0'
def generateBinaryStrings(n):
# Initialize a string of n zeros
# as our starting point
s = ['0'] * n
ans = []
stringRecur(0, s, ans)
return ans
if __name__ == "__main__":
n = 4
res = generateBinaryStrings(n)
for s in res:
print(s)
// C# program to Generate all binary
// strings without consecutive 1's
using System;
using System.Collections.Generic;
using System.Text;
class GfG {
// Recursive helper function to generate binary strings
static void stringRecur(int i, StringBuilder s, List<string> ans) {
// Base case: If we've filled all positions,
// add the string to results
if (i >= s.Length) {
ans.Add(s.ToString());
return;
}
// Case 1: Keep the current position as
// '0' and move to next position
stringRecur(i + 1, s, ans);
// Case 2: Try placing '1' at current position.
// Skip the next position when we place a '1'
// to avoid consecutive 1's
s[i] = '1';
// Skip next position to avoid consecutive 1's
stringRecur(i + 2, s, ans);
// Backtrack: Restore the current position back to '0'
s[i] = '0';
}
static List<string> generateBinaryStrings(int n) {
// Initialize a string of n zeros
// as our starting point
StringBuilder s = new StringBuilder();
for (int j = 0; j < n; j++) {
s.Append('0');
}
List<string> ans = new List<string>();
stringRecur(0, s, ans);
return ans;
}
static void Main(string[] args) {
int n = 4;
List<string> res = generateBinaryStrings(n);
foreach (string s in res) {
Console.WriteLine(s);
}
}
}
// JavaScript program to Generate all binary
// strings without consecutive 1's
// Recursive helper function to generate binary strings
function stringRecur(i, s, ans) {
// Base case: If we've filled all positions,
// add the string to results
if (i >= s.length) {
ans.push(s.join(''));
return;
}
// Case 1: Keep the current position as
// '0' and move to next position
stringRecur(i + 1, s, ans);
// Case 2: Try placing '1' at current position.
// Skip the next position when we place a '1'
// to avoid consecutive 1's
s[i] = '1';
// Skip next position to avoid consecutive 1's
stringRecur(i + 2, s, ans);
// Backtrack: Restore the current position back to '0'
s[i] = '0';
}
function generateBinaryStrings(n) {
// Initialize a string of n zeros
// as our starting point
let s = Array(n).fill('0');
let ans = [];
stringRecur(0, s, ans);
return ans;
}
let n = 4;
let res = generateBinaryStrings(n);
for (let s of res) {
console.log(s);
}
Output
0000 0001 0010 0100 0101 1000 1001 1010
Interesting Fact : The count of n length strings with no consecutive 1s is equal to (n+2)-th Fibonacci Number
Time Complexity: O(n 2^n), as at each step, we can consider 0 or 1. Please note that this is an upper bound. An exact bound would be O(n F(n+2)) where F(n+2) is (n+2)th Fibonacci Number.
Auxiliary Space: O(n) due to recursion call stack.