Sum of Beauty of All Substrings - Problem
The beauty of a string is the difference in frequencies between the most frequent and least frequent characters.
For example, the beauty of "abaacc" is 3 - 1 = 2.
Given a string s, return the sum of beauty of all of its substrings.
Input & Output
Example 1 — Basic Case
$
Input:
s = "aab"
›
Output:
2
💡 Note:
Substrings: "a"(beauty=0), "a"(beauty=0), "aa"(beauty=0), "ab"(beauty=1), "aab"(beauty=1), "b"(beauty=0). Total: 0+0+0+1+1+0 = 2
Example 2 — Single Character
$
Input:
s = "abc"
›
Output:
0
💡 Note:
All substrings have equal character frequencies (each char appears once in its substrings), so beauty is always 0
Example 3 — Repeated Characters
$
Input:
s = "aaaa"
›
Output:
0
💡 Note:
All substrings contain only 'a', so max_freq = min_freq, beauty = 0 for all substrings
Constraints
- 1 ≤ s.length ≤ 500
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with characters that may repeat
2
Process
For each substring, find max_freq - min_freq
3
Output
Sum of all beauty values
Key Takeaway
🎯 Key Insight: Beauty is the frequency gap between most and least common characters in each substring
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code