Given a positive integer N, the task is to find the number of binary strings of length N which contains “11” as a substring.
Input: N = 2
Explanation: The only string of length 2 that has “11” as a substring is “11”.
Input: N = 12
Approach: The idea is to derive the number of possibilities of having “11” as a substring for binary representations starting with 0 or 1 based on the following observations:
- If the first bit is 0, then the starting bit does not contribute to the string having “11” as a substring. Therefore, the remaining (N – 1) bits have to form a string having “11” as a substring.
- If the first bit is 1 and the following bit is also 1, then there exists 2(N – 2) strings having “11” as a substring.
- If the first bit is 1 but the following bit is 0, then a string having “11” as a substring can be formed with remaining (N – 2) bits.
- Therefore, the recurrence relation to generate all the binary strings of length N is:
dp[i] = dp[i – 1] + dp[i – 2] + 2(N – 2)
dp[i] is the string of length i having “11” as a substring.
and dp = dp = 0.
Follow the steps below to solve the problem:
- Initialize an array, say dp, of size (N + 1) and assign dp as 0 and dp as 0.
- Precompute the first N powers of 2 and store it in an array, say power.
- Iterate over the range [2, N] and update dp[i] as (dp[i – 1] + dp[i – 2] + power[i – 2]).
- After completing the above steps, print the value of dp[N] as the result.
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.