Python 1781.py
class Solution:
def beautySum(self, s: str) -> int:
result = 0
for i in range(len(s)):
have = [ 0 ] * 26
for j in range(i, len(s)):
c = ord(s[j]) - 97 # 97 = ord("a")
have[c] += 1
high = max(have)
low = min([ h for h in have if h > 0 ])
result += high - low
return result
Difficulty
and has an acceptance rate of about 70% (100k+ submissions).
Typical patterns to solve this problem:
- Counting
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method beautySum that calculates the cumulative “beauty” of all substrings of a given lowercase alphabetic string s. The beauty of a single substring is defined as the difference between the highest and lowest non-zero character frequencies within that substring. By iterating over every possible start and end index, the algorithm aggregates these differences into a final integer result.
Key Steps
Outer Loop and Result Accumulator
The algorithm begins by initializing an accumulator result to zero. It then iterates over each possible starting index i of a substring.
result = 0
for i in range(len(s)):
Frequency Array Initialization
For each new start position i, a fixed-size list have of length 26 (one entry per lowercase letter) is created and filled with zeros. This array will hold the running counts of characters as the end index expands.
have = [0] * 26
Inner Loop and Frequency Update
The inner loop moves the end index j from the current start i to the end of the string. For each character s[j], its alphabetical offset is computed with ord(s[j]) - 97, and the corresponding entry in have is incremented.
for j in range(i, len(s)):
c = ord(s[j]) - 97 # 97 = ord('a')
have[c] += 1
Determining Highest and Lowest Non-Zero Frequencies
After each character addition, the algorithm extracts the maximum frequency high from the entire have array. To find the minimum non-zero frequency low, it filters out zero entries and applies min. The difference high - low represents the beauty of the current substring, which is added to result.
high = max(have)
low = min([h for h in have if h > 0])
result += high - low
Final Return
When all start and end positions have been processed, the accumulated result is returned as the total beauty sum.
return result
Edge Cases Handled
When the input string is empty, the outer loop does not execute, leaving result at its initial value of zero, which correctly reflects that there are no substrings to evaluate.
For a single-character string, the inner loop runs once, the frequency array records a count of one for that character, and both high and low evaluate to one, yielding a beauty contribution of zero for that sole substring.
If the string consists of repeated instances of the same character, the frequency array will contain a single non-zero entry that grows with each extension of the substring. Since high and low will always be equal, each substring contributes zero to the total, which aligns with the definition of beauty.
When multiple distinct characters appear, the filtering step if h > 0 ensures that characters not present in the current substring do not affect the calculation of the minimum frequency, thereby correctly handling substrings where some letters are absent.
Performance Optimizations
The implementation leverages a constant-size array of length 26 to store character frequencies, avoiding the overhead of dynamic dictionary structures. This fixed array enables O(1) access and update for each character, which is crucial given the nested loop structure that processes every substring.
By updating the frequency array incrementally as the end index j advances, the code reuses the previously computed counts instead of recomputing frequencies from scratch for each new substring. This incremental approach reduces redundant work and keeps the inner loop work limited to a single addition and two aggregate operations (max and min).
The use of ord to convert characters to integer indices eliminates the need for string slicing or additional look-up tables, providing a lightweight and direct mapping from characters to array positions.
The filtering expression [h for h in have if h > 0] constructs a temporary list containing only the positive counts, allowing min to operate solely on relevant values. Although this creates a short-lived list, its size is bounded by the alphabet size (26), making the overhead negligible compared to the overall processing of substrings.
Overall, the combination of a fixed-size frequency array, incremental updates, and bounded auxiliary structures contributes to an efficient traversal of all possible substrings while maintaining concise and readable code.
ELI5 - Simplified Explanation
Imagine a long train made of colorful letter blocks. Each block has a letter of the alphabet on it. This code looks at every possible small train you can make by cutting a slice out of the big one.
To start, the code makes an empty checklist to keep track of how many times each letter appears in the little slice being looked at right now. It starts at the beginning of the train and looks at the first block. Then it adds another block to the group, then another, until it reaches the end. Every time a new block is added, the code checks the list to see which letter appears the most and which letter appears the least.
The code calculates the difference between the most frequent letter and the least frequent one for that specific slice. It keeps a running total of these differences for every single possible slice that can be made from the big train. By the time the code finishes looking at every slice starting from every point, it has a final number representing the total beauty of all those slices combined.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||
| WalkCCC | C++ | Python | Java | ||||||
| leetcode.ca | C++ | Python | JS | Java | Go | Rust | TS | ||
| Progiez | C++ | Python | Java | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, Rust, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| fsq | C++ | ||||||||
| haoel | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1184: Distance Between Bus Stops
- problem 1342: Number of Steps to Reduce a Number to Zero
- problem 1399: Count Largest Group
- problem 1496: Path Crossing
- problem 1646: Get Maximum in Generated Array
- problem 1893: Check if All the Integers in a Range Are Covered
- problem 2404: Most Frequent Even Element
- problem 2432: The Employee That Worked on the Longest Task
- problem 2451: Odd String Difference
- problem 2540: Minimum Common Value
- problem 609: Find Duplicate File in System
- problem 1169: Invalid Transactions
- problem 1711: Count Good Meals
- problem 1865: Finding Pairs With a Certain Sum
- problem 1871: Jump Game VII
- problem 2013: Detect Squares
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality