Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of beauty of all substrings in Python
Given a string, we need to find the sum of beauty of all its substrings. The beauty of a string is the difference between the frequencies of the most frequent and least frequent characters.
For example, if the string is "abaacc", the frequency of 'a' is 3 and 'b' is 1, so beauty = 3 - 1 = 2.
Problem Example
If the input string is "xxyzy", the substrings with non-zero beauty are:
- "xxy" ? beauty = 2 - 1 = 1
- "xxyz" ? beauty = 2 - 1 = 1
- "xxyzy" ? beauty = 2 - 1 = 1
- "xyzy" ? beauty = 2 - 1 = 1
- "yzy" ? beauty = 2 - 1 = 1
Total sum = 1 + 1 + 1 + 1 + 1 = 5
Algorithm
We use a nested loop approach to generate all possible substrings and calculate their beauty:
- Initialize result as 0
- For each starting position i, iterate through all ending positions j
- Extract substring from i to j and count character frequencies
- Calculate beauty as max frequency - min frequency
- Add beauty to the result
Implementation
from collections import Counter
def solve(s):
res = 0
for i in range(len(s)):
for j in range(i + 2, len(s) + 1):
c = Counter(s[i:j])
v = list(c.values())
if v: # Check if substring is not empty
res += (max(v) - min(v))
return res
s = "xxyzy"
print(solve(s))
5
Step-by-Step Breakdown
Let's trace through the algorithm with "xxyzy":
from collections import Counter
def solve_with_trace(s):
res = 0
print(f"Analyzing string: '{s}'")
print("-" * 40)
for i in range(len(s)):
for j in range(i + 2, len(s) + 1):
substring = s[i:j]
c = Counter(substring)
v = list(c.values())
beauty = max(v) - min(v) if v else 0
if beauty > 0:
print(f"Substring: '{substring}' ? Beauty: {beauty}")
res += beauty
print("-" * 40)
print(f"Total beauty sum: {res}")
return res
s = "xxyzy"
solve_with_trace(s)
Analyzing string: 'xxyzy' ---------------------------------------- Substring: 'xxy' ? Beauty: 1 Substring: 'xxyz' ? Beauty: 1 Substring: 'xxyzy' ? Beauty: 1 Substring: 'xyzy' ? Beauty: 1 Substring: 'yzy' ? Beauty: 1 ---------------------------------------- Total beauty sum: 5
Time Complexity
The algorithm has O(n³) time complexity:
- Two nested loops: O(n²) to generate all substrings
- Counter operation: O(n) for each substring
- Overall: O(n³)
Conclusion
This solution efficiently calculates the sum of beauty for all substrings by using nested loops and the Counter class. The beauty is determined by the difference between maximum and minimum character frequencies in each substring.
