Number of Beautiful Partitions Problem
Description
LeetCode Problem 2478.
You are given a string s that consists of the digits '1' to '9' and two integers k and minLength.
A partition of s is called beautiful if:
sis partitioned intoknon-intersecting substrings.- Each substring has a length of at least
minLength. - Each substring starts with a prime digit and ends with a non-prime digit. Prime digits are
'2','3','5', and'7', and the rest of the digits are non-prime.
Return the number of beautiful partitions of s. Since the answer may be very large, return it modulo 10^9 + 7.
A substring is a contiguous sequence of characters within a string.
Example 1:
Input: s = "23542185131", k = 3, minLength = 2
Output: 3
Explanation: There exists three ways to create a beautiful partition:
"2354 | 218 | 5131"
"2354 | 21851 | 31"
"2354218 | 51 | 31"
Example 2:
Input: s = "23542185131", k = 3, minLength = 3
Output: 1
Explanation: There exists one way to create a beautiful partition: "2354 | 218 | 5131".
Example 3:
Input: s = "3312958", k = 3, minLength = 1
Output: 1
Explanation: There exists one way to create a beautiful partition: "331 | 29 | 58".
Constraints:
1 <= k, minLength <= s.length <= 1000sconsists of the digits'1'to'9'.
Solution
Approach: Dynamic Programming with Prefix Sums
Let f[i][j] be the number of ways to split the first i characters into j beautiful parts, with f[0][0] = 1.
A part can end at position i only if s[i] (1-indexed) is not prime and either i is the end of the string or the next character is prime. If so, the last part starts after some position t <= i - minLength, so f[i][j] is the sum of f[t][j-1] over those t. Keep the prefix sums g[i][j] = f[0][j] + ... + f[i][j], which turns this into f[i][j] = g[i - minLength][j - 1]. Otherwise f[i][j] = 0.
If s does not start with a prime digit or ends with one, the answer is 0. The answer is f[n][k], taken modulo 10^9 + 7.
Complexity: O(n * k) time and O(n * k) space, where n is the length of s.
class Solution:
def beautifulPartitions(self, s: str, k: int, minLength: int) -> int:
primes = '2357'
if s[0] not in primes or s[-1] in primes:
return 0
mod = 10**9 + 7
n = len(s)
f = [[0] * (k + 1) for _ in range(n + 1)]
g = [[0] * (k + 1) for _ in range(n + 1)]
f[0][0] = g[0][0] = 1
for i, c in enumerate(s, 1):
if i >= minLength and c not in primes and (i == n or s[i] in primes):
for j in range(1, k + 1):
f[i][j] = g[i - minLength][j - 1]
for j in range(k + 1):
g[i][j] = (g[i - 1][j] + f[i][j]) % mod
return f[n][k]