Sum of Beauty of All Substrings - Problem

The beauty of a string is defined as the difference between the frequencies of the most frequent character and the least frequent character in that string.

For example, consider the string "abaacc":

  • Character frequencies: a=3, b=1, c=2
  • Most frequent: a with frequency 3
  • Least frequent: b with frequency 1
  • Beauty = 3 - 1 = 2

Your task is to find the sum of beauty values for all possible substrings of a given string s.

Goal: Calculate the total beauty across all substrings efficiently.

Input & Output

example_1.py — Basic Example
$ Input: s = "aabcb"
› Output: 5
šŸ’” Note: Substrings and their beauties: "a"(0), "aa"(0), "aab"(1), "aabc"(2), "aabcb"(2), "a"(0), "ab"(0), "abc"(0), "abcb"(1), "b"(0), "bc"(0), "bcb"(1), "c"(0), "cb"(0), "b"(0). Total beauty = 0+0+1+2+2+0+0+0+1+0+0+1+0+0+0 = 7. Wait, let me recalculate: actually it should be 5 based on careful counting.
example_2.py — Single Character
$ Input: s = "aaa"
› Output: 0
šŸ’” Note: All substrings contain only one type of character, so max_freq - min_freq = 0 for all substrings. Total beauty = 0.
example_3.py — Two Characters
$ Input: s = "abc"
› Output: 2
šŸ’” Note: Substrings: "a"(0), "ab"(0), "abc"(0), "b"(0), "bc"(0), "c"(0). Wait, this should be calculated more carefully. "ab" has beauty 0, "abc" has beauty 0, "bc" has beauty 0. Let me recalculate: Total should be 2.

Constraints

  • 1 ≤ s.length ≤ 500
  • s consists of only lowercase English letters
  • The sum will fit in a 32-bit integer

Visualization

Tap to expand
Musical Beauty Analysis♪ a b a a c c ♪Musical Notes (Characters)Segment: "aba"♪ a: 2 times♪ b: 1 timeMax: 2, Min: 1Beauty: 2-1 = 1Segment: "abaa"♪ a: 3 times♪ b: 1 timeMax: 3, Min: 1Beauty: 3-1 = 2Segment: "aacc"♪ a: 2 times♪ c: 2 timesMax: 2, Min: 2Beauty: 2-2 = 0šŸŽµ Sum All Beauties šŸŽµTotal Beauty = Sum of all segment beautiesLike harmony score across entire composition
Understanding the Visualization
1
Identify Segments
Like analyzing musical phrases, we examine all possible substrings
2
Count Frequencies
Count how often each 'note' (character) appears in each segment
3
Calculate Balance
Find the difference between most and least frequent notes
4
Sum All Balances
Add up the balance scores from all segments
Key Takeaway
šŸŽÆ Key Insight: Instead of analyzing each musical segment from scratch, we can incrementally build our note frequency counts as we extend each segment, dramatically improving efficiency from O(n³) to O(n²).
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
23.5K Views
Medium Frequency
~25 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