Number of Beautiful Partitions — LeetCode 2478 Python Solution

HardStringDynamic ProgrammingPrefix Sum
Problem
#2478
Pattern
Prefix Sum
Reading time
3 min

The problem

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: s is partitioned into k non-intersecting substrings.

Example

Input
s = "23542185131", k = 3, minLength = 2
Output
3
Explanation
There exists three ways to create a beautiful partition:

Python solution

Python
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]

Complexity

MeasureComplexity
TimeO(n \times k)
SpaceO(n \times k) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 2478. Number of Beautiful Partitions is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2478. Number of Beautiful Partitions?
LeetCode 2478. Number of Beautiful Partitions is rated Hard on LeetCode.
What is the time complexity of LeetCode 2478. Number of Beautiful Partitions?
The Python solution on this page runs in O(n \times k).
What is the space complexity of LeetCode 2478. Number of Beautiful Partitions?
The Python solution on this page uses O(n \times k) auxiliary space.
What topics does LeetCode 2478. Number of Beautiful Partitions cover?
LeetCode 2478. Number of Beautiful Partitions is tagged String, Dynamic Programming and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview