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"
is3 - 1 = 2
.
Given a string s
, return the sum of beauty of all of its substrings.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Naive
To solve this problem, we need to iterate through all substrings of the given string s
and calculate the beauty of each substring. Given that a substring’s beauty is the difference between the maximum and minimum frequency of its characters, we can follow a brute-force approach and optimise it to some extent.
Approach
- Generate All Substrings:
- Iterate over all possible substrings of
s
. - For each substring, construct a frequency count of characters.
- Iterate over all possible substrings of
- Calculate Beauty:
- For each substring, determine the maximum and minimum frequency of the characters.
- Calculate the beauty as the difference between the maximum and minimum counts.
- Sum the Beauty Values:
- Sum up the beauty values for all substrings to get the desired result.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^3)
, wheren
is the length of the strings
. This is because:- Generating all substrings takes
O(n^2)
time. - For each substring, calculating the beauty by counting character frequencies takes
O(n)
time.
- Generating all substrings takes
- 🧺 Space complexity:
O(1)
for the frequency array since it’s fixed at26
(for lowercase English letters) for every substring.