JavaScript Program to Generate all Binary Strings Without Consecutive 1’s
Last Updated :
31 May, 2024
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
So, let's see each of the approaches with its practical implementation.
Approach 1: Using Recursive Function
Here, the recursive function generates all the binary strings of the input size 'K' without consecutive 1's by actually appending the '0' and the '1' to the input string 'str'. In each step there, is the appending of 0 or 1, and the binary strings are stored in the res variable and printed using the log function.
Example: In this example, we will Generate all binary strings without consecutive 1’s in JavaScript using the Recursive Function.
JavaScript
let K = 5;
let res = "";
function binaryStr(str, n) {
if (n === K) {
res += str + " ";
return;
}
if (n === 0 || str[n - 1] === "0") {
binaryStr(str + "0", n + 1);
binaryStr(str + "1", n + 1);
} else {
binaryStr(str + "0", n + 1);
}
}
// Strings starting with 0
binaryStr("0", 1);
// Strings starting with 1
binaryStr("1", 1);
console.log(res.trim());
Output00000 00001 00010 00100 00101 01000 01001 01010 10000 10001 10010 10100 10101
Approach 2: Using Stack Data Structure
In this specified approach, we are using the Stack Data Structure where the empty stack is used initially and pushed, and the popping of the binary strings is done to make sure that there are no consecutive 1s in the string. Then we display the results in the descending sequence.
Example: In this example, we will Generate all binary strings without consecutive 1’s in JavaScript using the Stack Data Structure.
JavaScript
function binaryStr(K) {
let stack = [''];
let res = [];
while (stack.length > 0) {
let str = stack.pop();
if (str.length === K) {
res.push(str);
continue;
}
if (str[str.length - 1] === '1') {
stack.push(str + '0');
} else {
stack.push(str + '0');
stack.push(str + '1');
}
}
console.log(res.reverse().join(' '));
}
binaryStr(6);
Output000000 000001 000010 000100 000101 001000 001001 001010 010000 010001 010010 010100 010101 100000 100001 100010 100100 100101 101000 101001 101010
In this approach, we are using the builtin methods to generate all the binary strings by performing the loop and mathematical operations. We convert the decimal number to a binary string and make sure that there are no consecutive 1s included in the string. Then we print these strings using the log function.
Example: In this example, we will Generate all binary strings without consecutive 1’s in JavaScript using Math.pow(), toString(), padStart() and includes() Methods
JavaScript
function binaryStr(K) {
let results = [];
for (let i = 0; i < Math.pow(2, K); i++) {
let res = i.toString(2).padStart(K, "0");
if (!res.includes("11")) {
results.push(res);
}
}
console.log(results.join(" "));
}
binaryStr(4);
Output0000 0001 0010 0100 0101 1000 1001 1010
Approach 4: Using Backtracking
In this approach, we utilize backtracking to generate all binary strings of size K without consecutive 1's. We start with an empty string and recursively explore all possible choices for each position in the string, ensuring that we append '0' or '1' only if it does not result in consecutive 1's.
Example:
JavaScript
function generateBinaryStrings(K) {
let results = [];
function backtrack(str, index) {
if (str.length === K) {
results.push(str);
return;
}
// If the last character is '1', we can only append '0'
if (str[str.length - 1] === '1') {
backtrack(str + '0', index + 1);
}
// Otherwise, we can append either '0' or '1'
else {
backtrack(str + '0', index + 1);
backtrack(str + '1', index + 1);
}
}
// Start backtracking from an empty string
backtrack('', 0);
return results.join(' ');
}
console.log(generateBinaryStrings(4));
Output0000 0001 0010 0100 0101 1000 1001 1010
Similar Reads
JavaScript Program to Count Strings with Consecutive 1âs
Given a number n, count the Optimized number of n-length strings with consecutive 1s in them. Examples: Input : n = 2Output : 1There are 4 strings of length 2, thestrings are 00, 01, 10 and 11. Only the string 11 has consecutive 1's.Input : n = 3Output : 3There are 8 strings of length 3, thestrings
7 min read
JavaScript Program to Generate all Binary Strings From Given Pattern
In this article, we are going to learn about Generating all binary strings from a given pattern in JavaScript. Generating all binary strings from a given pattern involves creating a set of binary sequences that follow the pattern's structure, where specific positions in the sequences can be filled w
3 min read
JavaScript Program to FindNumber of Flips to make Binary String Alternate
In this problem, we aim to determine the minimum number of flips needed to transform a binary string into an alternating sequence of '0's and '1's. A flip refers to changing a '0' to '1' or a '1' to '0'. The objective is to find the most efficient way to achieve this alternating pattern. Examples: I
4 min read
JavaScript Program to Check if all Bits can be made Same by Single Flip
In this article, we will explore how to determine if it's possible to make all bits the same in a binary string by performing a single flip operation. We will cover various approaches to implement this in JavaScript and provide code examples for each approach. Examples: Input: 1101Output: YesExplana
5 min read
JavaScript Program for Min flips of continuous characters to make all characters same in a String
In this article, we will learn about Min flips of continuous characters to make all characters the same in a string using JavaScript. Min flips of continuous characters in a string refer to the minimum number of changes required to turn a sequence of adjacent characters into a uniform sequence, ensu
3 min read
JavaScript Program to Print all Subsequences of a String
A subsequence is a sequence that can be derived from another sequence by deleting zero or more elements without changing the order of the remaining elements. Subsequences of a string can be found with different methods here, we are using the Recursion method, Iteration method and Bit manipulation me
3 min read
JavaScript Program for Binary Representation of Next Number
Given a binary input that represents a binary representation of the positive number n, find a binary representation of n+1. We will try to find out this with the different approaches discussed below. Examples: Input : 10011 Output : 10100 Here n = (19)10 = (10011)2 next greater integer = (20)10 = (1
3 min read
PHP Program to Count number of binary strings without consecutive 1's
Write a PHP program for a given positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1s. Examples: Input: N = 2Output: 3Explanation: The 3 strings are 00, 01, 10 Input: N = 3Output: 5Explanation: The 5 strings are 000, 001, 010,
2 min read
Java Program to Convert Binary Code into Gray Code Without Using Recursion
Binary Code of a number is the representation of a number in Binary (base-2) number system. In Binary Number System, each number is expressed using only two literals (0 and 1). Each of these literals is called a bit. The binary number system is very useful in digital electronic circuits. Gray Code o
4 min read
Java Program to Convert Octal to Binary
Given an Octal number as input, the task is to convert that number into its Binary equivalent number. Example: Input: Octal Number = 513 Output: Binary equivalent value is: 101001011 Explanation : Binary equivalent value of 5: 101 Binary equivalent value of 1: 001 Binary equivalent value of 3: 011Oc
5 min read