How to use a bottom-up dynamic programming approach In Javascript
This approach iterates through each length of the binary strings from 2 to ‘n’, calculating the count of strings ending with zero and one separately. Then, it updates the total count accordingly. Finally, it returns the total count of binary strings with consecutive 1’s of length ‘n’.
// Function to count binary strings
// with consecutive 1's of length 'n'
function countBinaryStringsWithConsecutiveOnes(n) {
// Initialize variables to store counts
let countEndingWithZero = 1;
let countEndingWithOne = 1;
let totalCount = 1;
// Calculate counts for each length
for (let i = 2; i <= n; i++) {
let tempCountEndingWithZero = countEndingWithZero;
let tempCountEndingWithOne = countEndingWithOne;
// For strings ending with zero, they can be extended by either zero or one
countEndingWithZero = tempCountEndingWithZero + tempCountEndingWithOne;
// For strings ending with one, they can only be extended by zero
countEndingWithOne = tempCountEndingWithZero;
// Total count of strings of length 'i'
totalCount = countEndingWithZero + countEndingWithOne;
}
// Total count of binary strings with consecutive 1's of length 'n'
return totalCount;
}
// Driver code
console.log(countBinaryStringsWithConsecutiveOnes(11));
Output
233
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 = 2
Output : 1
There are 4 strings of length 2, the
strings are 00, 01, 10 and 11. Only the
string 11 has consecutive 1's.
Input : n = 3
Output : 3
There are 8 strings of length 3, the
strings are 000, 001, 010, 011, 100,
101, 110 and 111. The strings with
consecutive 1's are 011, 110 and 111.
Input : n = 5
Output : 19
Table of Content
- Naive Approach
- Optimized Approach
- Optimization