- 0
Notifications Mark All Read
- Login
- Get Prime
Count Binary Strings Without Consecutive Ones
Count Binary Strings Without Consecutive Ones
In Count Binary Strings Without Consecutive Ones problem we have to count strings of length n such that each character of the string can only be 1 or 0. And we should not count strings with ’11’ as a sub string. Here is a C++ implementation of both top down and bottom up approach.
Count Binary Strings Without Consecutive Ones Problem Statement
Given an integer n return the number of binary strings of length n such that they do not contain ’11’ as a sub string. The answer can be large so return the result modulo 1000000007.
Example:
Given n = 3
Output:
5
Explanation
The length 3 possible binary strings are – 000, 001, 010, 011, 100, 101 , 110, 111
Out of these 011, 110 and 111 contain 11 as a sub string. Therefore the result is 5.
Count Binary Strings Without Consecutive Ones Solution
Solution 1 (Top Down dynamic programming)
For writing the top down solution we will write a function F(id , prev).
F(id , prev) means number of binary strings of length n with prev filled at (n+1)th place. Now we have to decide our transitions.
The transitions will be :-
f(n,prev) = f(n-1,0) + f(n-1,1) if(prev ==0)
or
f(n,prev) = f(n-1,0) if(prev==1)
We will be using a memo table to speed up the solution and avoid recalculation of values.
C++ Code
Output:
2
3
Solution 2 (Bottom up Dynamic Programming)
For writing bottom up dp solution we will create a dp table as dp[n+1][2].
dp[i][0] gives us the count of binary strings of length i with ith charactor filled 0. dp[i][0] = dp[i-1][0] + dp[i-1][1]
dp[i][1] gives us the count of binary strings of length i with ith charactor filled 1. dp[i][1] – dp[i-1][0] (Because we don’t need consecutive ones).
Our answer will be dp[n][0]+dp[n][1].
C++ Code
Output:
3
5
Login/Signup to comment