#2478

Number of Beautiful Partitions

Hard
StringDynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k)
Space
O(1)
O(n * k)
💡

Intuition

Time O(n * k)Space O(n * k)

The optimal approach uses dynamic programming to efficiently count valid partitions. Instead of checking all combinations, we build up solutions using previously computed results.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP array where dp[i] represents the number of ways to partition the string up to index i.
  2. 2Step 2: Iterate through the string and for each position, check if it can form a valid substring ending at that position.
  3. 3Step 3: Update the DP array based on previous valid partitions.
solution.py19 lines
1# Full working Python code
2MOD = 10**9 + 7
3primes = {'2', '3', '5', '7'}
4non_primes = {'1', '4', '6', '8', '9'}
5
6def beautiful_partitions(s, k, minLength):
7    n = len(s)
8    dp = [[0] * (k + 1) for _ in range(n)]
9    for i in range(n):
10        if i + 1 >= minLength and s[i] in non_primes:
11            for j in range(1, k + 1):
12                if j == 1:
13                    if s[0] in primes:
14                        dp[i][j] = 1
15                else:
16                    for l in range(minLength, i + 2):
17                        if s[l - 1] in non_primes and s[l - minLength] in primes:
18                            dp[i][j] = (dp[i][j] + dp[l - 2][j - 1]) % MOD
19    return dp[n - 1][k]

Complexity note: The complexity is linear with respect to the length of the string and the number of partitions due to the nested loops iterating through the string and partitions.

  • 1Understanding prime and non-prime digits is crucial.
  • 2Dynamic programming can significantly reduce the number of checks needed.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.