LeetCode 2478: Number of Beautiful Partitions Solution

Master LeetCode problem 2478 (Number of Beautiful Partitions), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2478. Number of Beautiful Partitions

Problem Explanation

Explanation:

To solve this problem, we can iterate through all possible partitions of the string s and check if each partition satisfies the conditions of being beautiful. We can use dynamic programming to keep track of the number of beautiful partitions ending at each index of the string.

  1. Initialize a 2D DP array where dp[i][j] represents the number of beautiful partitions ending at index i with j substrings.
  2. Iterate through each index i of the string s and each possible number of substrings j.
  3. For each index i, calculate the number of beautiful partitions ending at index i with j substrings based on the previous results.
  4. Update the DP array accordingly.
  5. Finally, return the sum of all beautiful partitions with k substrings and a total length of at least minLength. :

Solution Code

class Solution {
    public int countBeautifulString(String s, int k, int minLength) {
        int mod = 1000000007;
        int n = s.length();
        int[][] dp = new int[n + 1][k + 1];
        
        dp[0][0] = 1;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= k; j++) {
                int primeCount = 0;
                for (int l = i; l > 0 && i - l + 1 >= minLength; l--) {
                    if (s.charAt(l - 1) == '2' || s.charAt(l - 1) == '3' || s.charAt(l - 1) == '5' || s.charAt(l - 1) == '7') {
                        primeCount++;
                    }
                    if (primeCount > 0) {
                        dp[i][j] = (dp[i][j] + dp[l - 1][j - 1]) % mod;
                    }
                }
            }
        }
        
        int result = 0;
        for (int i = 0; i <= n; i++) {
            result = (result + dp[i][k]) % mod;
        }
        
        return result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2478 (Number of Beautiful Partitions)?

This page provides optimized solutions for LeetCode problem 2478 (Number of Beautiful Partitions) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2478 (Number of Beautiful Partitions)?

The time complexity for LeetCode 2478 (Number of Beautiful Partitions) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2478 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2478 in Java, C++, or Python.

Back to LeetCode Solutions