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
Beauty Calculation for String "aab"aabInput String"a" → 0"aa" → 0"aab" → 1"a" → 0"ab" → 1"b" → 0All Substrings with Their Beauty ValuesSum = 0+0+1+0+1+0 = 2Final Answer
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
Asked in
Amazon 25 Microsoft 18
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen