Sum of Beauty of All Substrings

The **beauty** of a string is the difference between the frequency of its most frequent character and the frequency of its least frequent character (counting only characters that appear). For example, the beauty of `"abaacc"` is `3 - 1 = 2`. Given a string `s`, return the sum of the beauty of all of its substrings.

30:00

Sum of Beauty of All Substrings
medium
Free written solution
Topics
Companies

The beauty of a string is the difference between the frequency of its most frequent character and the frequency of its least frequent character (counting only characters that appear).

For example, the beauty of "abaacc" is 3 - 1 = 2.

Given a string s, return the sum of the beauty of all of its substrings.

Example 1:
Input: {"s":"aabcb"}
Output: 5
Constraints:
  • 1≤s.length≤5001 \leq s.\text{length} \leq 500

  • s consists of only lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"aabcb"}

Every substring s[i..j] has a beauty: its highest letter count minus its lowest. Fix a start i, then grow j one letter at a time so the counts only ever go up.

s, current substring s[i..j]

a

0

a

1

b

2

c

3

b

4

letter counts in the substring

no substring yet

beauty = max count - min count

beauty of s[i..j] (row i, column j)

total = 0

Variables
VariableValue
n5
total0
DepthFunction Call
Stack empty
0/21