Skip to content
Related Articles
Open in App
Not now

Related Articles

Python Program to Count number of binary strings without consecutive 1’s

Improve Article
Save Article
  • Last Updated : 16 Jun, 2022
Improve Article
Save Article

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


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: Please solve it on “PRACTICE ” first, before moving on to the solution.


# 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
# This code is contributed
# by Anant Agarwal.



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

Please refer complete article on Count number of binary strings without consecutive 1’s for more details!

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!