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:
1
💡 Note:
Substrings: "a"(beauty=0), "aa"(beauty=0), "aab"(beauty=1), "a"(beauty=0), "ab"(beauty=0), "b"(beauty=0). Total: 0+0+1+0+0+0 = 1
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code