Calculate sum of beauty (max freq - min freq) over all substrings.
Problem Statement
Examples
Input: s = "aabcb"
Output: 5
Explanation: Combining the input according to Sum of Beauty of All Substrings logic yields 5.
Input: s = "aabcbaa"
Output: 17
Explanation: Combining the input according to Sum of Beauty of All Substrings logic yields 17.
Complexity
Time Complexity: O(N² * 26)
Space Complexity: O(1)
Hints
Editorial & Approach
Problem Overview & Intuition
For every starting index i, as we extend the endpoint j, we maintain an incremental 26-character frequency table. Computing max - min across non-zero counts takes O(26) = O(1) time per substring, leading to an overall O(26 * N²) time complexity.
Step-by-Step Approach
- Initialize
totalBeauty = 0. - Outer loop
ifrom0tos.length - 1. - Reset frequency array
freq = new Array(26).fill(0). - Inner loop
jfromitos.length - 1: - Increment
freq[s.charCodeAt(j) - 97]++. - Compute
maxFandminFamong positive entries infreq. - Add
maxF - minFtototalBeauty. - Return
totalBeauty.
Optimal Implementation (JavaScript)
function beautySum(s) {
let totalBeauty = 0;
for (let i = 0; i < s.length; i++) {
const freq = new Array(26).fill(0);
for (let j = i; j < s.length; j++) {
freq[s.charCodeAt(j) - 97]++;
let maxF = 0, minF = Infinity;
for (let k = 0; k < 26; k++) {
if (freq[k] > 0) {
maxF = Math.max(maxF, freq[k]);
minF = Math.min(minF, freq[k]);
}
}
totalBeauty += (maxF - minF);
}
}
return totalBeauty;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- Substrings of length <= 2: beauty is 0 or 1.
- All identical characters: beauty is always 0.