![]() |
VOOZH | about |
Given a string s of length n consisting of digits from '0' to '9'. The task is to determine the total number of possible ways to partition the string into k substrings such that :
Examples:
Input: s = "432387429", m = 2, k = 3
Output: 3
Explanation: Following are valid partitions of the string s
43|23|87429, 4323|87|429, 43|2387|429Input: s = "546521", m = 3, k = 2,
Output: 0
Explanation: There is no way to partition the given string.
Table of Content
The idea is to explore all possible ways to partition the string into k substrings with minimum length m. The function starts from the beginning of the string and tries to create valid partitions by checking the digit parity conditions. At each step, it recursively explores potential partitions by moving the starting point forward and reducing the number of remaining partitions while ensuring each substring meets the specified constraints of starting with an even digit and ending with an odd digit.
Let countWays(i, k, s) represent the number of ways to partition s into k substrings starting at index i.
Base Cases:
- if length of remaining substring (s.length - i) is less than m, return 0.
- if k == 1 and the current substring is valid, return 1.
countWays(i, k, s) = countWays(j, k-1, s) where j is from i + m (to maintain minimum length of m for current substring) to last index and s[j] is an even integer and s[j-1] is an odd integer.
3
If we notice carefully, we can observe that the above recursive solution holds the following two properties of Dynamic Programming:
1. Optimal Substructure: Number of ways to make k substrings at index i, i.e., countWays(i, k, s), depends on the optimal solutions of the subproblems countWays(j, k-1, s) where j lies between i+m and s.length. By combining these optimal substructures, we can efficiently calculate number of ways to make k substrings at index i.
2. Overlapping Subproblems: While applying a recursive approach in this problem, we notice that certain subproblems are computed multiple times.
3
The idea is to fill the DP table from bottom to up. For each index i and partitions j, the dynamic programming relation is as follows:
- If string is not valid (does not start with even integer or length is less than m), set dp[i][j] = 0.
- If j == 1 and string is valid, set dp[i][j] = 1.
- Else dp[i][j] = sum(dp[x][j-1]) for all x in range [i+m, s.length].
3
In previous approach of dynamic programming, we observe that for calculating dp[i][j], we only need previous column dp[i][j-1]. There is no need to store all previous states.
3
Time Complexity: O(k*n*n), due to the 3 nested for loops: outer loop (from 1 to k), inner loop ( n-1 to 0 ) , innermost loop ( In the worst case, the innermost loop executes about n - i iterations, which is roughly n for each iteration of i)
Space Complexity: O(n), both vectors prev and curr takes O(n) space as they store values for each index of the string.