To solve this problem, we need to understand what beauty means for a substring. The beauty is the difference between how often the most frequent character appears and how often the least frequent (but present) character appears in that substring.
We consider every possible substring of the input string. For each substring, we count how many times each character appears. We ignore characters that have a count of 0, and then find the difference between the highest and lowest frequency among the characters that do appear.
Let’s understand this through different types of input:
- Case 1 – Normal string (e.g., "aabcb"):
There are substrings where characters appear with different frequencies. For example, in "aab", 'a' appears twice, 'b' once → beauty = 1. We do this for every substring and keep adding up their beauty values.
- Case 2 – All same characters (e.g., "aaaa"):
Every substring has all characters the same, so the highest and lowest frequencies are equal. Beauty = 0 for all of them.
- Case 3 – Short strings like "ab" or "a":
In "ab", both characters appear once, so no frequency difference → beauty = 0. In "a", there's only one character → beauty = 0.
- Case 4 – Empty string ""
There are no substrings to evaluate, so the total beauty is 0.
This problem involves many substrings, but we can optimize the solution by using a frequency array (of size 26 for each character) and reusing it while expanding the substring window. In each iteration, we quickly find the max and min (non-zero) frequencies and calculate the beauty.
By combining smart counting with substring expansion, we can solve this efficiently even for longer strings. The time complexity is roughly O(n²) but works well with optimization.