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
Sum of Beauty of All Substrings INPUT String s = "aab" a a b 0 1 2 All Substrings: "a" "a" "b" "aa" "ab" "aab" Red = contributes beauty Beauty = max_freq - min_freq (only if min_freq > 0) ALGORITHM STEPS 1 Iterate all substrings Use nested loops i, j 2 Track char frequencies Use array of size 26 3 Find max and min freq Skip if min = 0 4 Add beauty to sum sum += max - min Calculation Table Substr Freq Beauty "a","a","b" 1-1 0 "aa" 2-2 0 "ab" a:1,b:1 1-1=0 "aab" a:2,b:1 2-1=1 FINAL RESULT Beauty Contributions: "a" 0 "a" 0 "b" 0 "aa" 0 "ab" 1 "aab" 1 Total Sum 2 OK - Output: 2 Key Insight: Optimized Frequency Tracking: Instead of recalculating frequencies for each substring, extend the previous substring's frequency array. For each starting index i, incrementally add characters and update frequencies in O(1), reducing overall complexity from O(n^3) to O(n^2 * 26). TutorialsPoint - Sum of Beauty of All Substrings | Optimized Frequency Tracking
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