714002. Count Binary Strings With No Consecutive 1s

Hard

Count Binary Strings With No Consecutive 1s

Summary

Given a binary string, count the number of strings that can be formed by appending zeros and ones without having any consecutive 1s. This problem is related to number theory and involves the concept of Fibonacci series.

Detailed Explanation

To solve this problem, we will use the concept of Fibonacci series. A Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding numbers, usually starting with 0 and 1. In this case, we can consider the length of the binary string as the current term in the Fibonacci sequence.

We start by initializing dp array to store the count of strings that have no consecutive 1s for each length from 0 to n (the length of the given binary string). We set dp[0] = dp[1] = 1 because there is only one way to form a binary string with no consecutive 1s of length 0 and 1, which is by having an empty string or a single 0.

Now, for each length i from 2 to n, we calculate dp[i] as the sum of dp[i-1] and dp[i-2]. This is because for each binary string with no consecutive 1s of length i, either the last bit is 0 (in which case we can append any number of zeros or ones to get a string of length i), or the last two bits are 01 (in which case we can append any number of zeros or ones to get a string of length i).

Finally, we return dp[n] as the count of binary strings that can be formed by appending zeros and ones without having any consecutive 1s.

Here is a step-by-step breakdown of the solution:

int count = 1;
for (int i = 0; i < n; i++) {
    if (i == 0 || str[i-1] != '1') {
        count++;
    }
}
return count;

Time complexity: O(n) Space complexity: O(1)

Optimized Solutions

Java

View on GeeksforGeeks
public class Solution {
    public int countStrings(String str) {
        if (str.length() == 0) return 2;
        if (str.length() == 1) return 2;
        int count = 1;
        for (int i = 0; i < str.length(); i++) {
            if (i == 0 || str.charAt(i-1) != '1') {
                count++;
            }
        }
        return count;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.