Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1781. Sum of Beauty of All Substrings

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)

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;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.