Given an K and a matrix Q[][] consisting of queries of the form {N, M}, the task for each query is to count the number of strings possible of all lengths from Q[i][0] to Q[i][1] satisfying the following properties:
Since the answer can be quite large, compute the answer by mod 109 + 7.
Examples:
Input_: K = 3, Q[][] = {{1, 3}} _
Output_: 4 _
Explanation:
_All possible strings of length 1 : {“1”} _
_All possible strings of length 2 : {“11”} _
_All possible strings of length 3 : {“111”, “000”} _
Therefore, a total of 4 strings can be generated.
Input_: K = 3, Q[][] = {{1, 4}, {3, 7}} _
_Output: _
_7 _
_24 _
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Naive Approach:
Follow the steps below to solve the problem:
Time Complexity:_ O(N*Q) _
Auxiliary Space:_ O(N)_
Efficient Approach:
The above approach can be optimized using Prefix Sum Array. Follow the steps below:
Below is the implementation of the above approach:
// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
**using**
**namespace**
std;
**const**
**int**
N = 1e5 + 5;
**const**
**int**
MOD = 1000000007;
**long**
**int**
dp[N];
// Function to calculate the
// count of possible strings
**void**
countStrings(``**int**
K,
vector<vector<``**int**``> > Q)
{
// Initialize dp[0]
dp[0] = 1;
// dp[i] represents count of
// strings of length i
**for**
(``**int**
i = 1; i < N; i++) {
dp[i] = dp[i - 1];
// Add dp[i-k] if i>=k
**if**
(i >= K)
dp[i]
= (dp[i] + dp[i - K]) % MOD;
}
// Update Prefix Sum Array
**for**
(``**int**
i = 1; i < N; i++) {
dp[i] = (dp[i] + dp[i - 1]) % MOD;
}
**for**
(``**int**
i = 0; i < Q.size(); i++) {
**long**
**int**
ans
= dp[Q[i][1]] - dp[Q[i][0] - 1];
**if**
(ans < 0)
ans = ans + MOD;
cout << ans << endl;
}
}
// Driver Code
**int**
main()
{
**int**
K = 3;
vector<vector<``**int**``> > Q
= { { 1, 4 }, { 3, 7 } };
countStrings(K, Q);
**return**
0;
}
Output:
7
24
Time Complexity:_ O(N + Q) _
_Auxiliary Space: _O(N)
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.
#dynamic programming #mathematical #strings #binary-string #prefix-sum