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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read