How to useStack Data Structure in Javascript
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.
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);
Output
000000 000001 000010 000100 000101 001000 001001 001010 010000 010001 010010 010100 010101 100000 100001 100010 100100 100101 101000 101001 101010
JavaScript Program to Generate all Binary Strings Without Consecutive 1’s
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
Table of Content
- Approach 1: Using Recursive Function
- Approach 2: Using Stack Data Structure
- Approach 3: Using Iteration and padStart() Method
- Approach 4: Using Backtracking
So, let’s see each of the approaches with its practical implementation.