Sum of Beauty of All Substrings Problem
#1781
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1781.
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.
Example 1:
Input: s = "aabcb"
Output: 5
Explanation: The substrings with non-zero beauty are ["aab","aabc","aabcb","abcb","bcb"], each with beauty equal to 1.
Example 2:
Input: s = "aabcbaa"
Output: 17
Constraints:
1 <= s.length <=500sconsists of only lowercase English letters.
Solution
Approach: Enumeration + Counting
Fix the left end i of the substring and extend the right end j one character at a time, keeping a count of each letter in s[i..j]. The beauty of the current substring is the largest count minus the smallest non-zero count, found by scanning the 26 counters. Add it to the answer for every j.
Complexity: O(26 · n2) time and O(26) space, where n is the length of s.
from collections import Counter
class Solution:
def beautySum(self, s: str) -> int:
ans, n = 0, len(s)
for i in range(n):
cnt = Counter()
for j in range(i, n):
cnt[s[j]] += 1
ans += max(cnt.values()) - min(cnt.values())
return ans