The Number of Beautiful Partitions problem gives you a numeric string and integers k and minLength. Partition the string into exactly k substrings such that each substring starts with a prime digit and ends with a non-prime digit, and has length ≥ minLength. Count valid partitions modulo 10^9+7. This hard coding problem uses DP with prefix sum optimization on valid partition points.
Google asks this hard problem because it combines DP partition counting with prefix sums for O(1) transition cost — a technique that reduces O(n²k) DP to O(nk). The string, dynamic programming, and prefix sum interview pattern is comprehensively tested, and the prime/non-prime digit conditions add a layer of constraint checking.
DP with prefix sums. Define dp[i][j] = number of ways to partition the first i characters into j groups. Transition: the j-th group ends at position i and starts at some position s, where s has a prime digit, i has a non-prime digit, and i - s + 1 ≥ minLength. Use prefix sums prefDP[i][j-1] to efficiently sum over all valid starting positions. Prime digits: {2,3,5,7}. Non-prime: {1,4,6,8,9,0}.
s="23542185131", k=3, minLength=2.
Partition DP problems where transitions sum over a range of previous states always benefit from prefix sum optimization. Build the prefix sum array in parallel with the DP. For "count partitions into k parts with each part satisfying a condition," first identify valid start/end positions (prime/non-prime check), then apply DP with prefix sums. Practice similar problems like "count ways to partition a string with given prefix/suffix constraints" to build fluency with this combined technique.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Minimum White Tiles After Covering With Carpets | Hard | Solve | |
| Find the Original Typed String II | Hard | Solve | |
| Number of Ways to Select Buildings | Medium | Solve | |
| Jump Game VII | Medium | Solve | |
| Count The Repetitions | Hard | Solve |