LeetCode 1781: Sum of Beauty of All Substrings Solution

Master LeetCode problem 1781 (Sum of Beauty of All Substrings), a medium 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.

1781. Sum of Beauty of All Substrings

Problem Explanation

Explanation

To solve this problem, we can iterate through all possible substrings of the given string and calculate the beauty of each substring. We can maintain a frequency array for each substring to keep track of the frequency of each character. Then, we can calculate the beauty as the difference between the maximum and minimum frequency in the frequency array. Finally, we sum up the beauty of all substrings to get the total sum of beauty of all substrings.

Time complexity: O(n^3) where n is the length of the input string s
Space complexity: O(26) = O(1)

Solution Code

class Solution {
    public int beautySum(String s) {
        int n = s.length();
        int sum = 0;
        
        for (int i = 0; i < n; i++) {
            int[] freq = new int[26];
            for (int j = i; j < n; j++) {
                freq[s.charAt(j) - 'a']++;
                int maxFreq = 0, minFreq = Integer.MAX_VALUE;
                for (int k = 0; k < 26; k++) {
                    if (freq[k] > 0) {
                        maxFreq = Math.max(maxFreq, freq[k]);
                        minFreq = Math.min(minFreq, freq[k]);
                    }
                }
                sum += maxFreq - minFreq;
            }
        }
        
        return sum;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1781 (Sum of Beauty of All Substrings)?

This page provides optimized solutions for LeetCode problem 1781 (Sum of Beauty of All Substrings) 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 1781 (Sum of Beauty of All Substrings)?

The time complexity for LeetCode 1781 (Sum of Beauty of All Substrings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1781 on DevExCode?

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

Back to LeetCode Solutions