The Wayback Machine - https://web.archive.org/web/20240707023624/https://www.geeksforgeeks.org/count-number-binary-strings-without-consecutive-1s/
Open In App

Count number of binary strings without consecutive 1’s

Last Updated : 30 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s.

Examples: 

Input:  N = 2
Output: 3
// The 3 strings are 00, 01, 10
Input: N = 3
Output: 5
// The 5 strings are 000, 001, 010, 100, 101
Recommended Practice

This problem can be solved using Dynamic Programming. Let a[i] be the number of binary strings of length i which do not contain any two consecutive 1’s and which end in 0. Similarly, let b[i] be the number of such strings which end in 1. We can append either 0 or 1 to a string ending in 0, but we can only append 0 to a string ending in 1. This yields the recurrence relation: 

a[i] = a[i - 1] + b[i - 1]
b[i] = a[i - 1]

The base cases of above recurrence are a[1] = b[1] = 1. The total number of strings of length i is just a[i] + b[i].
Following is the implementation of above solution. In the following implementation, indexes start from 0. So a[i] represents the number of binary strings for input length i+1. Similarly, b[i] represents binary strings for input length i+1.

Implementation:

C++




// C++ program to count all distinct binary strings
// without two consecutive 1's
#include <iostream>
using namespace std;
 
int countStrings(int n)
{
    int a[n], b[n];
    a[0] = b[0] = 1;
    for (int i = 1; i < n; i++)
    {
        a[i] = a[i-1] + b[i-1];
        b[i] = a[i-1];
    }
    return (a[n-1] + b[n-1])%1000000007;
}
 
 
// Driver program to test above functions
int main()
{
    cout << countStrings(3) << endl;
    return 0;
}


Java




import java.io.*;
class Subset_sum
{
    static  int countStrings(int n)
    {
        int a[] = new int [n];
        int b[] = new int [n];
        a[0] = b[0] = 1;
        for (int i = 1; i < n; i++)
        {
            a[i] = a[i-1] + b[i-1];
            b[i] = a[i-1];
        }
        return (a[n-1] + b[n-1])%1000000007;
    }
    /* Driver program to test above function */
    public static void main (String args[])
    {
          System.out.println(countStrings(3));
    }
}/* This code is contributed by Rajat Mishra */


Python3




# Python program to count
# all distinct binary strings
# without two consecutive 1's
 
def countStrings(n):
 
    a=[0 for i in range(n)]
    b=[0 for i in range(n)]
    a[0] = b[0] = 1
    for i in range(1,n):
        a[i] = a[i-1] + b[i-1]
        b[i] = a[i-1]
     
    return a[n-1] + b[n-1]
 
# Driver program to test
# above functions
 
print(countStrings(3))
 
# This code is contributed
# by Anant Agarwal.


C#




// C# program to count all distinct binary
// strings without two consecutive 1's
using System;
 
class Subset_sum
{
    static int countStrings(int n)
    {
        int []a = new int [n];
        int []b = new int [n];
        a[0] = b[0] = 1;
        for (int i = 1; i < n; i++)
        {
            a[i] = a[i-1] + b[i-1];
            b[i] = a[i-1];
        }
        return (a[n-1] + b[n-1])%1000000007;
    }
     
    // Driver Code
    public static void Main ()
    {
        Console.Write(countStrings(3));
    }
}
 
// This code is contributed by nitin mittal


Javascript




<script>
 
// JavaScript program to count all
// distinct binary strings
// without two consecutive 1's
function countStrings(n)
{
    let a = [];
    let b = [];
    a[0] = b[0] = 1;
     
    for(let i = 1; i < n; i++)
    {
        a[i] = a[i - 1] + b[i - 1];
        b[i] = a[i - 1];
    }
    return (a[n-1] + b[n-1])%1000000007;
}
 
// Driver code
document.write(countStrings(3));
 
// This code is contributed by rohan07
 
</script>


PHP




<?php
// PHP program to count all distinct
// binary stringswithout two
// consecutive 1's
 
function countStrings($n)
{
    $a[$n] = 0;
    $b[$n] = 0;
    $a[0] = $b[0] = 1;
    for ($i = 1; $i < $n; $i++)
    {
        $a[$i] = $a[$i - 1] +
                 $b[$i - 1];
        $b[$i] = $a[$i - 1];
    }
    return ($a[$n - 1] +
           $b[$n - 1])%1000000007;
}
 
    // Driver Code
    echo countStrings(3) ;
 
// This code is contributed by nitin mittal
?>


Output

5




Time Complexity: O(N)
Auxiliary Space: O(N)

Source: 

If we take a closer look at the pattern, we can observe that the count is actually (n+2)’th Fibonacci number for n >= 1. The Fibonacci Numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, …. 

n = 1, count = 2  = fib(3)
n = 2, count = 3 = fib(4)
n = 3, count = 5 = fib(5)
n = 4, count = 8 = fib(6)
n = 5, count = 13 = fib(7)
................

Therefore we can count the strings in O(Log n) time also using the method 5 here.

Another method :-

From the above method it is clear that we only want just previous value in the for loop which we can also do by replacing the array with the variable.

Below is the implementation of the above approach:- 

C++




// C++ program to count all distinct binary strings
// without two consecutive 1's
#include <bits/stdc++.h>
using namespace std;
 
int countStrings(int n)
{
    int a = 1, b = 1;
    for (int i = 1; i < n; i++) {
        // Here we have used the temp variable because we
        // want to assign the older value of a to b
        int temp = a + b;
        b = a;
        a = temp;
    }
    return (a + b)%1000000007;
}
 
// Driver program to test above functions
int main()
{
    cout << countStrings(3) << endl;
    return 0;
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Java




import java.io.*;
class Subset_sum {
    static int countStrings(int n)
    {
        int a = 1;
        int b = 1;
        for (int i = 1; i < n; i++) {
            // Here we have used the temp variable because
            // we want to assign the older value of a to b
            int temp = a + b;
            b = a;
            a = temp;
        }
        return (a + b)%1000000007;
    }
    /* Driver program to test above function */
    public static void main(String args[])
    {
        System.out.println(countStrings(3));
    }
}
 
// This code is contributed by Aditya Kumar (adityakumar129)


Python3




class Subset_sum :
    @staticmethod
    def  countStrings( n) :
        a = 1
        b = 1
        i = 1
        while (i < n) :
            # Here we have used the temp variable because
            # we want to assign the older value of a to b
            temp = a + b
            b = a
            a = temp
            i += 1
        return (a + b)%1000000007
       
    # Driver program to test above function
    @staticmethod
    def main( args) :
        print(Subset_sum.countStrings(3))
     
 
if __name__=="__main__":
    Subset_sum.main([])
     
    # This code is contributed by aadityaburujwale.


C#




// Include namespace system
using System;
 
public class Subset_sum
{
    public static int countStrings(int n)
    {
        var a = 1;
        var b = 1;
        for (int i = 1; i < n; i++)
        {
           
            // Here we have used the temp variable because
            // we want to assign the older value of a to b
            var temp = a + b;
            b = a;
            a = temp;
        }
        return (a + b)%1000000007;
    }
   
    // Driver program to test above function
    public static void Main(String[] args)
    {
        Console.WriteLine(Subset_sum.countStrings(3));
    }
}
 
// This code is contributed by aadityaburujwale.


Javascript




function countStrings(n){
    var a = 1;
    var b = 1;
    for(let i=1;i<n;i++){
        // Here we have used the temp variable because
        // we want to assign the older value of a to b
        var temp = a + b;
        b = a;
        a = temp;
    }
    return (a + b)%1000000007;
}
 
console.log(countStrings(3));
 
// This code is contributed by lokesh


Output

5




Time Complexity: O(N)
Auxiliary Space: O(1)

Related Post : 
1 to n bit numbers with no consecutive 1s in binary representation.

Another Useful Approach:-

Fibonacci in Log (n) without using Matrix Exponentiation

As for calculating the n we can express it as the product of n/2 and n/2 ((n/2+1) for n is odd) as they are independent ,now as there are the cases when we combining these two half values to get full length there may be occurrence of consecutive 1’s at the joining. So we have to subtract those cases to get the final result.

f(n)=f(n/2)*f(n/2) - (those values which has consecutive 1's at the joining part)

To find the values of consecutive 1’s at the intersection

As moving from n to n+1 ,the difference between them is the only value which have 0’s at the end as 0 values only double the values . And 0’s values at the end will only give two results as 0 and 1 because if last element is 1 then we can’t get 1 after it as then they become two consecutive.

So,

f(n)-f(n-1) = 0's value at the last position of f(n-1) = 1's value at the last position of f(n)

Finally ,

If n is even:

f(n)=f(n/2)*f(n/2) - (f(n/2)-f(n/2-1))(f(n/2)-f(n/2-1))

If n is odd:

f(n)=f(n/2)*f(n/2+1) - (f(n/2)-f(n/2-1))(f(n/2+1)-f(n/2))

And we will store pre-calculated value using map.

C++




// Fibonacci in log(n)
// Easy code
// Without using matrix exponentiation
#include <bits/stdc++.h>
using namespace std;
 
class Solution {
  public:
  //storing the pre-calculated value
  //what we called DP
    map<long long int,long long int>mp;
    int countStrings(long long int N) {
        // Code here
        if(N==0)return 1;
        if(N==1)return 2;
        if(N==2)return 3;
        long long int mod=1e9+7;
        long long int a=mp[N/2-1]=((mp[N/2-1])?mp[N/2-1]:countStrings(N/2-1))%mod,b=mp[N/2]=((mp[N/2])?mp[N/2]:countStrings(N/2))%mod,c=mp[N/2+1]=((mp[N/2+1])?mp[N/2+1]:countStrings(N/2+1))%mod;
        if(N%2)
        return mp[N]=((b*c%mod)-((c-b)*(b-a)%mod)+mod)%mod;
        return mp[N]=((b*b%mod)-((b-a)*(b-a)%mod)+mod)%mod;
    }
};
 
int main() {
    int t;
    cin >> t;
    while (t--) {
        long long int N;
        cin >> N;
        Solution obj;
        cout << obj.countStrings(N) << endl;
    }
}
// Article contributed by Chetan Chaudhary


Java




import java.util.*;
 
class Solution {
    // Storing the pre-calculated value
    // using a HashMap for DP
    Map<Long, Long> mp = new HashMap<>();
 
    long countStrings(long N) {
        // Base cases
        if (N == 0) return 1;
        if (N == 1) return 2;
        if (N == 2) return 3;
         
        long mod = (long)1e9 + 7;
         
        // Check if the value is already present in the map
        if (mp.containsKey(N)) {
            return mp.get(N);
        }
         
        // Recursive calls and memoization
        long a = mp.getOrDefault(N/2 - 1, countStrings(N/2 - 1)) % mod;
        long b = mp.getOrDefault(N/2, countStrings(N/2)) % mod;
        long c = mp.getOrDefault(N/2 + 1, countStrings(N/2 + 1)) % mod;
         
        // Calculations
        long result;
        if (N % 2 == 1)
            result = ((b * c % mod) - ((c - b) * (b - a) % mod) + mod) % mod;
        else
            result = ((b * b % mod) - ((b - a) * (b - a) % mod) + mod) % mod;
         
        // Store the result in the map for future use
        mp.put(N, result);
         
        return result;
    }
}
 
public class Main {
    public static void main(String[] args) {
        long N = 10;
        Solution obj = new Solution();
        System.out.println(obj.countStrings(N));
    }
}


Python3




class Solution:
    def __init__(self):
        self.mp = {}
 
    def countStrings(self, N):
        if N == 0:
            return 1
        if N == 1:
            return 2
        if N == 2:
            return 3
 
        mod = 10**9 + 7
 
        a = self.mp.get(N//2-1, self.countStrings(N//2-1)) % mod
        b = self.mp.get(N//2, self.countStrings(N//2)) % mod
        c = self.mp.get(N//2+1, self.countStrings(N//2+1)) % mod
 
        if N % 2:
            return (b*c - (c-b)*(b-a) + mod) % mod
        return (b*b - (b-a)*(b-a) + mod) % mod
 
 
# t = int(input())
t=1
while t > 0:
    # N = int(input())
    N=10
    obj = Solution()
    print(obj.countStrings(N))
    t -= 1
# Code contributed by Chetan Chaudhary


C#




using System;
using System.Collections.Generic;
 
class Solution {
    // Dictionary to store memoized values
    static Dictionary<long, long> mp = new Dictionary<long, long>();
 
    // Recursive function to count strings
    public static long countStrings(long N) {
        // Base cases:
        if (N == 0) return 1;
        if (N == 1) return 2;
        if (N == 2) return 3;
         
        long mod = (long)1e9 + 7;
         
        // Check if the value for N is already memoized
        long a = mp.ContainsKey(N / 2 - 1) ? mp[N / 2 - 1] : countStrings(N / 2 - 1);
        long b = mp.ContainsKey(N / 2) ? mp[N / 2] : countStrings(N / 2);
        long c = mp.ContainsKey(N / 2 + 1) ? mp[N / 2 + 1] : countStrings(N / 2 + 1);
         
        // Calculations based on whether N is even or odd
        if (N % 2 == 1) {
            // Memoize and return result for odd N
            return mp[N] = ((b * c % mod) - ((c - b) * (b - a) % mod) + mod) % mod;
        } else {
            // Memoize and return result for even N
            return mp[N] = ((b * b % mod) - ((b - a) * (b - a) % mod) + mod) % mod;
        }
    }
}
 
class Program {
    static void Main(string[] args) {
        long N = 10;
        Console.WriteLine(Solution.countStrings(N));
    }
}


Javascript




class Solution {
  constructor() {
    // Storing the pre-calculated value
    // using a Map for DP
    this.mp = new Map();
  }
 
  countStrings(N) {
    // Base cases
    if (N === 0n) return 1n;
    if (N === 1n) return 2n;
    if (N === 2n) return 3n;
     
    const mod = 1000000007n; // Use 1000000007n instead of 1e9+7n
     
    // Check if the value is already present in the map
    if (this.mp.has(N)) {
      return this.mp.get(N);
    }
     
    // Recursive calls and memoization
    const a = this.mp.has(N / 2n - 1n) ? this.mp.get(N / 2n - 1n) : this.countStrings(N / 2n - 1n);
    const b = this.mp.has(N / 2n) ? this.mp.get(N / 2n) : this.countStrings(N / 2n);
    const c = this.mp.has(N / 2n + 1n) ? this.mp.get(N / 2n + 1n) : this.countStrings(N / 2n + 1n);
     
    // Calculations
    let result;
    if (N % 2n === 1n)
      result = ((b * c % mod) - ((c - b) * (b - a) % mod) + mod) % mod;
    else
      result = ((b * b % mod) - ((b - a) * (b - a) % mod) + mod) % mod;
     
    // Store the result in the map for future use
    this.mp.set(N, result);
     
    return result;
  }
}
 
const N = 10n; // Use BigInt literal for N
const obj = new Solution();
console.log(obj.countStrings(N).toString());
 
 
// This code is contributed by rambabuguphka


Output

144




Time Complexity: O(log N)
Auxiliary Space  : O(log N)

For n=10 , the output is 144.

We can calculate Fibonacci in log(n) using above result .



Previous Article
Next Article

Similar Reads

Count possible binary strings of length N without P consecutive 0s and Q consecutive 1s
Given three integers N, P, and Q, the task is to count all possible distinct binary strings of length N such that each binary string does not contain P times consecutive 0’s and Q times consecutive 1's. Examples: Input: N = 5, P = 2, Q = 3Output: 7Explanation: Binary strings that satisfy the given conditions are { “01010”, “01011”, “01101”, “10101”
15+ min read
Count number of binary strings without consecutive 1’s : Set 2
Given a positive integer N, the task is to count all possible distinct binary strings of length N such that there are no consecutive 1’s. Examples: Input: N = 5 Output: 5 Explanation: The non-negative integers &lt;= 5 with their corresponding binary representations are: 0 : 0 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 Among them, only 3 has two consecutiv
15+ min read
Count of Binary strings having at most X consecutive 1s and Y consecutive 0s
Given two integers N and M (1 ≤ N, M ≤ 100) denoting the total number of 1s and 0s respectively. The task is to count the number of possible arrangements of these 0s and 1s such that any arrangement has at most X consecutive 1s and Y consecutive 0s (1 ≤ X, Y ≤ 10). As the number of arrangements can be very large, compute the answer with MODULO 109+
7 min read
Generate a Binary String without any consecutive 0's and at most K consecutive 1's
Given two integers N and M, the task is to construct a binary string with the following conditions : The Binary String consists of N 0's and M 1'sThe Binary String has at most K consecutive 1's.The Binary String does not contain any adjacent 0's. If it is not possible to construct such a binary string, then print -1. Examples: Input: N = 5, M = 9,
7 min read
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 1010Idea behind that is IF string ends with '1' then we put only '0' at the end. IF string ends with '0' then we put both '0' and '1' at the end of
15+ min read
Count of binary strings of length N with even set bit count and at most K consecutive 1s
Given two integers N and K, the task is to find the number of binary strings of length N having an even number of 1's out of which less than K are consecutive.Examples: Input: N = 4, K = 2 Output: 4 Explanation: The possible binary strings are 0000, 0101, 1001, 1010. They all have even number of 1's with less than 2 of them occurring consecutively.
12 min read
Count of binary strings of length N having equal count of 0's and 1's and count of 1's &ge; count of 0's in each prefix substring
Given an integer N, the task is to find the number of possible binary strings of length N with an equal frequency of 0's and 1's in which frequency of 1's are greater or equal to the frequency of 0's in every prefix substring. Examples: Input: N = 2Output: 1Explanation:All possible binary strings of length 2 are {"00", "01", "10" and "11"}. Out of
7 min read
Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
Given three integers, N, K and M. The task is to find out the number of binary strings of length N which always starts with 1, in which there can be at most M consecutive 1's or 0's and they alternate exactly K times.Examples: Input: N = 5, K = 3, M = 2 Output: 3 The 3 configurations are: 11001 10011 11011 Explanation: Notice that the groups of 1's
12 min read
Postorder traversal of Binary Tree without recursion and without stack
Given a binary tree, perform postorder traversal. Prerequisite - Inorder/preorder/postorder traversal of tree We have discussed the below methods for postorder traversal. 1) Recursive Postorder Traversal. 2) Postorder traversal using Stack. 2) Postorder traversal using two Stacks. Approach 1 The approach used is based on using an unordered set to k
15 min read
Make given Binary Strings equal by replacing two consecutive 0s with single 1 repeatedly
Given two binary strings str1 and str2, the task is to check whether it is possible to convert str1 to str2 by combining two consecutive 0's into a single 1 repeatedly. Examples: Input: str1 = "00100", str2 = "111" Output: Yes Explanation: Combine first two zeros to one and combine last two zeros to one. Input: str1 = "00", str2 = "000" Output: No
6 min read
three90RightbarBannerImg