Given three integers, N, K and M. The task is to find out the number of binary strings of length N which always starts with 1, in which there can be at most M consecutive 1’s or 0’s and they alternate exactly K times.
Input: N = 5, K = 3, M = 2
The 3 configurations are:
Notice that the groups of 1’s and 0’s alternate exactly K times
Input: N = 7, K = 4, M = 3
- Sub-problem: DP[i][j] represents the number of binary strings upto length i having j alternating groups till now. So, to calculate dp[N][K] if we know the value of dp[n-j][k-1], then we can easily get the result by summing up the sub-problem value over j = 1 to m (DP[N][K] represents the final answer).
- Optimal substructure:
- By following the top-down DP approach:
As we can have a group which can be atmost of the length M, so we iterate on every possible length and recur with new N and decreasing K by 1, as a new group is formed. Solution to sub-problem is cached and summed up to give final result dp[N][K].
- Base Case:
- When N is 0 and K is 0, then return 1
- When N is 0 but K is not 0, then return 0
- When N is not 0 but K is 0, then return 0
- When both are negative, return 0
Below is the implementation of above approach:
Time complexity: O(N*K*M)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.