Given a number n, count number of n length strings with consecutive 1’s in them.
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
The reverse problem of counting strings without consecutive 1’s can be solved using Dynamic Programming (See the solution here). We can use that solution and find the required count using below steps.
1) Compute number of binary strings without consecutive 1’s using the approach discussed here. Let this count be c.
2) Count of all possible binary strings with consecutive 1’s is 2^n where n is input length.
3) Total binary strings with consecutive 1 is 2^n – c.
Below is implementation of above steps.
Time complexity of above solution is O(n). We can optimize above solution to work in O(Logn).
If we take a closer look at the pattern of counting strings without consecutive 1’s, 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 = 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 = 24 - fib(7) ................
We can find n’th Fibonacci Number in O(Log n) time (See method 4 here).
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Count number of binary strings without consecutive 1's
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Count All Palindrome Sub-Strings in a String | Set 1
- Count binary strings with twice zeros in first half
- Count of non-overlapping sub-strings "101" and "010" in the given binary string
- Check if bits of a number has count of consecutive set bits in increasing order
- Count binary strings with k times appearing adjacent two set bits
- Pairs of complete strings in two sets of strings
- Longest Consecutive Subsequence
- Check if a string has m consecutive 1's or 0's
- 1 to n bit numbers with no consecutive 1s in binary representation.
- 1 to n bit numbers with no consecutive 1s in binary representation
- Fibbinary Numbers (No consecutive 1s in binary)
- Check if a binary string contains consecutive same or not
- Maximum consecutive one’s (or zeros) in a binary array
Improved By : jit_t