Understanding the Problem
We are given a string, and we need to calculate the total beauty of all its substrings. But what does "beauty" mean in this context?
The beauty of a substring is defined as the difference between the highest frequency and the lowest frequency (excluding zero) of characters present in that substring.
So for each possible substring, we:
- Count how many times each character appears.
- Ignore characters with zero frequency.
- Calculate the difference between the maximum and minimum frequencies among the present characters.
We need to do this for every possible substring of the string and add up all the beauty values.
Step-by-Step Solution with Example
Step 1: Initialize total beauty counter
We'll keep a counter to store the total beauty of all substrings. Let’s call it totalBeauty
.
Step 2: Loop through all possible substrings
We use two nested loops: the outer loop sets the starting index of the substring, and the inner loop expands the end index.
Step 3: Maintain a character frequency count
As we expand the substring, we maintain a frequency array of size 26 (for each lowercase English letter).
Step 4: For each substring, compute beauty
After updating the frequency array:
- Extract all non-zero frequencies.
- Find the maximum and minimum among them.
- Beauty = max - min
- Add this to
totalBeauty
Step 5: Example with string "aabcb"
Let's go through a few substrings:
- "a" → freq: {a:1} → max = 1, min = 1 → beauty = 0
- "aa" → freq: {a:2} → max = 2, min = 2 → beauty = 0
- "aab" → freq: {a:2, b:1} → max = 2, min = 1 → beauty = 1
- "aabc" → freq: {a:2, b:1, c:1} → max = 2, min = 1 → beauty = 1
- ... and so on
We repeat this for all substrings and sum the beauty values.
Edge Cases
Case 1: All characters are the same
Example: "aaaa"
Every substring has the same character only, so max and min frequency are equal → beauty = 0 for all substrings.
Case 2: All characters are unique
Example: "abc"
Substrings like "ab", "bc", or "abc" have equal frequency for each character → beauty = 0.
But substrings like "a" or "b" still count as well, with beauty = 0.
Case 3: Short strings
Example: "a" → Only one character → max = min = 1 → beauty = 0
Example: "ab" → Both characters appear once → max = min = 1 → beauty = 0
Case 4: Empty string
No substrings to evaluate → total beauty = 0
Finally
This problem is a great exercise in brute-force with optimization. Even though the naive approach is O(n³), we can optimize to roughly O(n²) by reusing frequency arrays as we expand the substring.
Always remember to handle edge cases and think about the substring growth patterns. For large strings, this frequency-count-based method helps manage performance effectively.
Comments
Loading comments...