JavaScript Program to Count Strings with Consecutive 1’s
Last Updated :
23 Jul, 2025
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
Naive Approach:
- We've created a variable called "ans," which serves as a counter to keep track of how many strings contain two consecutive ones.
- Our approach involves generating all possible binary strings of a specified length using a recursive technique that involves picking and not picking of elements.
- Once we've generated these strings, we examine each one to determine if it contains two or more consecutive ones.
- If so, we increment the "ans" variable by 1 to keep count.
- In the end, we simply output the value stored in the "ans" variable, which represents the total number of strings with at least two consecutive ones.
Example: This example shows the use of the above-explained approach.
JavaScript
//Function to count binary strings
//with consecutive 1's of length 'n'
function countBinaryStringsWithConsecutiveOnes(
n, currentIndex, currentString, answer) {
// If we have reached the end of the string
if (currentIndex == n) {
let count = 0;
let tempCount = 0;
// Calculate the maximum consecutive 1's count
for (let i = 0; i < n; i++) {
if (
currentString.charAt(i) == "1") {
tempCount++;
} else {
// Reset the count
tempCount = 0;
}
// Update the maximum count
count = Math.max(count, tempCount);
}
// If the maximum count is greater than
// or equal to 2 increment the answer
if (count >= 2) {
answer[0]++;
}
return;
}
// Recursively generate binary strings
// by appending '0' and '1'
countBinaryStringsWithConsecutiveOnes(
n, currentIndex + 1, currentString + "0", answer);
countBinaryStringsWithConsecutiveOnes(
n, currentIndex + 1, currentString + "1", answer);
}
// Driver code
let answer = [0];
countBinaryStringsWithConsecutiveOnes(11, 0, "", answer);
console.log(answer[0]); // Print the total count
Time Complexity: O((2^n) * n), “2^n” for generating all strings, and “n” for traversing each string to count the maximum number of consecutive ones.
Auxiliary Space: O(n),Recursion Stack Space.
Optimized Approach:
To address the reverse problem of counting strings that don't contain consecutive 1's, we can utilize a Dynamic Programming solution, as explained in a separate solution (see here). We can leverage that solution to find the count we need by following these steps:
- Calculate the number of binary strings without consecutive 1's using the method outlined in the mentioned solution. Let's denote this count as "c."
- The total count of all possible binary strings of length "n" is 2^n.
- To find the total count of binary strings with consecutive 1's, subtract "c" from 2^n.
Example: This example shows the use of the above-explained approach.
JavaScript
// Function to count binary strings
//without consecutive 1's of length 'n'
function countBinaryStringsWithoutConsecutiveOnes(n) {
// Initialize arrays to store counts
// 'endingWithZero' represents counts ending with 0
// 'endingWithOne' represents counts ending with 1
let endingWithZero = [];
let endingWithOne = [];
endingWithZero[0] =
endingWithOne[0] = 1;
// Calculate counts for each length
for (let i = 1; i < n; i++) {
endingWithZero[i] =
endingWithZero[i - 1] +
endingWithOne[i - 1];
endingWithOne[i] =
endingWithZero[i - 1];
}
// Calculate the total count of binary strings
// Without consecutive 1's of length 'n'
return (
(1 << n) - endingWithZero[n - 1] - endingWithOne[n - 1]
);
}
// Driver Code
console.log(
countBinaryStringsWithoutConsecutiveOnes(11)
);
Time Complexity: O(n)
Auxiliary Space: O(n)
Optimization:
The time complexity of the previous solution is O(n). We can enhance the efficiency of the solution to operate in O(Logn) time. When we closely examine the pattern of counting strings without consecutive 1's, we can discern that the count is, in fact, the (n+2)th Fibonacci number for n >= 1. The Fibonacci Numbers sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, and so on.
n = 1, count = 0 = 21 - fib(3)
n = 2, count = 1 = 22 - fib(4)
n = 3, count = 3 = 23 - fib(5)
n = 4, count = 8 = 24 - fib(6)
n = 5, count = 19 = 25 - fib(7)
................
This optimization allows us to calculate the count much more efficiently using the Fibonacci sequence.
Example: This example shows the use of the above-explained approach.
JavaScript
// Fibonacci Series using Optimized
// Matrix Exponentiation Function
// that returns the nth Fibonacci number
function fib(n) {
// Initialize the base matrix
let F = [
[1, 1],
[1, 0],
];
// Handle the case when n is 0
if (n === 0) {
return 0;
}
// Calculate F^n using optimized
// matrix exponentiation
power(F, n - 1);
// The result is in the top-left element of F
return F[0][0];
}
// Function to multiply two matrices
function multiply(F, M) {
let x = F[0][0] * M[0][0] +
F[0][1] * M[1][0];
let y = F[0][0] * M[0][1] +
F[0][1] * M[1][1];
let z = F[1][0] * M[0][0] +
F[1][1] * M[1][0];
let w = F[1][0] * M[0][1] +
F[1][1] * M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
// Optimized version of matrix exponentiation
function power(F, n) {
if (n <= 1) {
return;
}
let M = [
[1, 1],
[1, 0],
];
power(F, Math.floor(n / 2));
multiply(F, F);
if (n % 2 !== 0) {
multiply(F, M);
}
}
// Driver code
let n = 11;
console.log(Math.pow(2, n) - fib(n + 2));
Time Complexity: O(logN)
Using a bottom-up dynamic programming approach:
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'.
JavaScript
// 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));
Dynamic Programming Approach
This method efficiently counts the desired binary strings by iterating through each length of the string from 2 to n, maintaining counts of strings ending with '0' and strings ending with '1'. Here's how it works:
Example:
JavaScript
function countBinaryStringsWithConsecutiveOnes(n) {
let countEndingWithZero = 1;
let countEndingWithOne = 1;
let totalCount = 1;
for (let i = 2; i <= n; i++) {
let tempCountEndingWithZero = countEndingWithZero;
let tempCountEndingWithOne = countEndingWithOne;
countEndingWithZero = tempCountEndingWithZero + tempCountEndingWithOne;
countEndingWithOne = tempCountEndingWithZero;
totalCount = countEndingWithZero + countEndingWithOne;
}
return totalCount;
}
console.log(countBinaryStringsWithConsecutiveOnes(11));
Similar Reads
Java Program to Count Number of Vowels in a String In java, the string is a sequence of characters and char is a single digit used to store variables. The char uses 2 bytes in java. In java, BufferedReader and InputStreamReader are used to read the input given by the user from the keyboard. Then readLine() is used for reading a line. The java.io pac
4 min read
Java Program to Count Number of Digits in a String The string is a sequence of characters. In java, objects of String are immutable. Immutable means that once an object is created, it's content can't change. Complete traversal in the string is required to find the total number of digits in a string. Examples: Input : string = "GeeksforGeeks password
2 min read
Java Program to Count the Total Number of Vowels and Consonants in a String Given a String count the total number of vowels and consonants in this given string. Assuming String may contain only special characters, or white spaces, or a combination of all. The idea is to iterate the string and checks if that character is present in the reference string or not. If a character
2 min read
Count valid strings that contains '0', '1' or '2' Given an integer n(1 <= n <= 105), the task is to count valid string S of length n, which contains characters '0', '1', or '2' only. For a valid string, it must follow the below conditions. There should not be more than K1 occurrences of '0'.There should not be more than K2 consecutive '1's. (
15+ min read
Techniques to Find Consecutive 1s or 0s in a Python String We are given a binary string and a number m, and we have to check if the string has m consecutive 1âs or 0âs. Below are a few examples to understand the problem statement clearly. Examples:Input: str = â001001â, m = 2 Output: TrueExplanation: the string have 2 consecutive 0s Input: str = â1000000001
4 min read
Java Program to Print all Unique Words of a String Java program to print all unique words present in the string. The task is to print all words occurring only once in the string. Illustration: Input : Welcome to Geeks for Geeks. Output : Welcome to for Input : Java is great.Python is also great. Output : Java Python also Methods: This can be done in
4 min read