Sum of Beauty of All Substrings (LeetCode 1781): Solution and Explanation
The beauty of a string is the count of its most frequent letter minus the count of its least frequent letter, counting only letters that appear. Given a lowercase string of up to 500 characters, add up the beauty of every substring.
Intuition
There are about n^2 / 2 substrings, which is only 125,250 for n = 500. Visiting each one is fine as long as measuring a substring does not cost another factor of n.
Fix the start i and let the end j walk right. Each step adds exactly one letter, so the letter counts of s[i..j] are the counts of s[i..j-1] with one slot bumped. The counts never need to be rebuilt, and the max and min come from a scan of only 26 slots.
Approach: Fixed start, growing end, 26 counters
- Set
total = 0. - For each start
i, reset a 26-slot count array. - For each end
jfromiton - 1, add one to the count ofs[j]. - Scan the 26 counts for the largest value and the smallest non-zero value, and add their difference to
total. - Return
total.
Step-by-step example
s = "aabcb"
- Start i = 0: "a" and "aa" have one letter each, beauty 0. "aab" has a:2, b:1, beauty 1. "aabc" has a:2, b:1, c:1, beauty 1. "aabcb" has a:2, b:2, c:1, beauty 1. Row total 3.
- Start i = 1: "a", "ab", "abc" all have equal counts, beauty 0. "abcb" has b:2 against a:1 and c:1, beauty 1. Row total 1.
- Start i = 2: "b", "bc" give 0, "bcb" has b:2, c:1, beauty 1. Row total 1.
- Starts 3 and 4: "c", "cb" and "b" all give 0.
- The total is 3 + 1 + 1 + 0 + 0 = 5.
Code: Python, Java, C++
1class Solution:
2 def beautySum(self, s: str) -> int:
3 total = 0
4 for i in range(len(s)):
5 freq = [0] * 26
6 for j in range(i, len(s)):
7 freq[ord(s[j]) - ord('a')] += 1
8 total += max(freq) - min(f for f in freq if f > 0)
9 return total1class Solution {
2 public int beautySum(String s) {
3 int total = 0;
4 for (int i = 0; i < s.length(); i++) {
5 int[] freq = new int[26];
6 for (int j = i; j < s.length(); j++) {
7 freq[s.charAt(j) - 'a']++;
8 int hi = 0, lo = Integer.MAX_VALUE;
9 for (int f : freq) {
10 if (f > 0) {
11 hi = Math.max(hi, f);
12 lo = Math.min(lo, f);
13 }
14 }
15 total += hi - lo;
16 }
17 }
18 return total;
19 }
20}1class Solution {
2public:
3 int beautySum(string s) {
4 int total = 0;
5 int n = s.size();
6 for (int i = 0; i < n; i++) {
7 int freq[26] = {0};
8 for (int j = i; j < n; j++) {
9 freq[s[j] - 'a']++;
10 int hi = 0, lo = INT_MAX;
11 for (int f : freq) {
12 if (f > 0) {
13 hi = max(hi, f);
14 lo = min(lo, f);
15 }
16 }
17 total += hi - lo;
18 }
19 }
20 return total;
21 }
22};Time and space complexity
O(26 * n^2)
There are n(n + 1) / 2 substrings and each one costs one count update plus a scan of 26 slots.
O(1)
Only one array of 26 counters and the running total are kept.
Other approaches
Count every substring from scratch (time O(n^3), space O(1))
Build a new count map for each of the n^2 substrings. Each build costs O(n), so the whole thing is O(n^3), about 20 million steps at n = 500.
Track max and min with a count-of-counts table (time O(n^2), space O(n))
Keep how many letters have each count so the max is updated in O(1) as counts grow. The min still needs care because a new letter drops it back to 1, and the gain over a 26-slot scan is small.
Common mistakes
- Taking the minimum over all 26 slots, which is almost always 0. Only letters that appear in the substring count.
- Rebuilding the counts for every (i, j) pair instead of extending the counts of the previous substring, which adds a factor of n.
- Counting distinct substrings only. Every substring position counts, so "a" at index 0 and "a" at index 1 are both included.
Frequently asked questions
Can the answer overflow a 32-bit integer?
No. A substring of length L has beauty at most L - 1, and summing that over all substrings of a 500-character string stays around 20 million, far below 2^31.
Why is the beauty of a single-letter substring 0?
Its only letter is both the most and the least frequent, so the difference is 0. The same holds for any substring where all letters appear equally often, such as "abc".
Is there a way to avoid the 26-slot scan?
Yes, with a count-of-counts structure, but 26 is a small constant and the simple scan is fast enough for n = 500.