Given an integer N, the task is to count the number of binary strings possible of length N such that they don’t contain “111” as a substring. The answer could be large so print answer modulo 109 + 7.
Input: N = 3
All possible substring are “000”, “001”,
“010”, “011”, “100”, “101” and “110”.
“111” is not a valid string.
Input N = 16
Approach: Dynamic programming can be used to solve this problem. Create a dp array where dp[i][j] will store the count of possible substrings such that 1 appears j times consecutively upto the ith index. Now, the recurrence relations will be:
dp[i] = dp[i – 1] + dp[i – 1] + dp[i – 1]
dp[i] = dp[i – 1]
dp[i] = dp[i – 1]
And the base cases will be dp = 1, dp = 1 and dp = 0. Now, the required count of strings will be dp[N] + dp[N] + dp[N].
Below is the implementation of the above approach:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Length of the largest substring which have character with frequency greater than or equal to half of the substring
- Number of binary strings such that there is no substring of length ≥ 3
- Count number of binary strings of length N having only 0's and 1's
- Number of non-decreasing sub-arrays of length greater than or equal to K
- Count of Binary strings of length N having atmost M consecutive 1s or 0s alternatively exactly K times
- Number of Binary Strings of length N with K adjacent Set Bits
- Find the number of binary strings of length N with at least 3 consecutive 1s
- Count the number of Special Strings of a given length N
- Count the number of subsequences of length k having equal LCM and HCF
- Count the number of strings in an array whose distinct characters are less than equal to M
- Length of the longest substring with equal 1s and 0s
- Count number of binary strings without consecutive 1’s : Set 2
- Count number of binary strings without consecutive 1's
- Length of longest subarray with product greater than or equal to 0
- Count of same length Strings that exists lexicographically in between two given Strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.