Python Program to Count number of binary strings without consecutive 1'

In this article, we will learn about counting binary strings of length N that don't contain consecutive 1's. This is a classic dynamic programming problem that follows the Fibonacci pattern.

Problem statement ? We are given a positive integer N, and we need to count all possible distinct binary strings of length N such that no two consecutive 1's exist in the string.

Approach

We can solve this using dynamic programming by considering two cases ?

  • a[i] = number of valid strings of length i ending with 0
  • b[i] = number of valid strings of length i ending with 1

The recurrence relation is ?

  • a[i] = a[i-1] + b[i-1] (we can append 0 after both 0 and 1)
  • b[i] = a[i-1] (we can append 1 only after 0 to avoid consecutive 1's)

Example

# count the number of strings
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]

# main
n = 5
print("The number of strings:", countStrings(n))

Output

The number of strings: 13
Binary Strings of Length 3 (Without Consecutive 1's) Valid Strings: 000 001 010 100 101 Invalid Strings: 011 (consecutive 1's) 110 (consecutive 1's) 111 (consecutive 1's) Total valid strings for n=3: 5 Pattern: 1, 2, 3, 5, 8, 13... (Fibonacci)

How It Works

For n=1: strings are "0" and "1" (count = 2)

For n=2: strings are "00", "01", "10" (count = 3, excluding "11")

For n=3: valid strings are "000", "001", "010", "100", "101" (count = 5)

Space-Optimized Version

def countStrings(n):
    if n == 1:
        return 2
    
    prev_a, prev_b = 1, 1
    
    for i in range(2, n + 1):
        curr_a = prev_a + prev_b
        curr_b = prev_a
        prev_a, prev_b = curr_a, curr_b
    
    return prev_a + prev_b

# Test with different values
for i in range(1, 7):
    print(f"n={i}: {countStrings(i)} strings")
n=1: 2 strings
n=2: 3 strings
n=3: 5 strings
n=4: 8 strings
n=5: 13 strings
n=6: 21 strings

Conclusion

The count of binary strings without consecutive 1's follows the Fibonacci sequence starting from the third term. This dynamic programming solution has O(n) time complexity and can be optimized to O(1) space complexity.

Updated on: 2026-03-25T06:55:08+05:30

364 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements