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 Generate n-bit Gray Codes
In this article, we are going to learn about Generate n-bit Gray Codes in JavaScript.Generating n-bit Gray Codes in JavaScript means creating a sequence of binary numbers of length n where each adjacent number differs by only one bit, typically starting with 0 and 1. There are several methods that c
3 min read
JavaScript Program to Find iâth Index Character in a Binary String Obtained After n Iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes â01â and 1 becomes â10â. Find the (based on indexing) index character in the string after the nth iteration. Input: m = 5, n = 2, i = 3Output: 1Input: m = 3, n = 3, i = 6Output: 1Approach 1
6 min read
JavaScript Program to Find First Set Bit
The rightmost bit in a binary representation of a number that is set to 1 is called the "First Set Bit". It indicates the lowest significant bit where the value changes from 0 to 1. Examples: Input: N = 18Output: 2Explanation: Binary representation of 18 is 010010,the first set bit from the right si
3 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 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
JavaScript Program to Check if a Number is Sparse or Not
A number is considered sparse if it does not have any consecutive ones in its binary representation. Example: Input: n=21Output: TrueExplanation: there are no consecutive 1s in the binary representation (10101). Therefore, 21 is a sparse number.Input: n=22Output: FalseExplanation: there are consecut
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