⬅ Previous Topic
Edit Distance ProblemNext Topic ⮕
Reverse Each Word in a String - Optimal Approach⬅ Previous Topic
Edit Distance ProblemNext Topic ⮕
Reverse Each Word in a String - Optimal ApproachTopic Contents
Given a string s
, your task is to find the sum of beauty for all its substrings.
The beauty of a substring is defined as the difference between the highest frequency character and the lowest frequency character (ignoring characters that do not appear).
For example, in substring "aabcb"
, the frequencies are: a → 2, b → 2, c → 1. So the beauty is 2 - 1 = 1
.
You need to compute this value for every possible substring of s
and return the total sum of all these beauties.
totalBeauty = 0
.i
of the string.count[26]
for characters 'a' to 'z'.j
≥ i
, do:s[j]
.maxFreq
and minFreq
from the count array (ignoring 0s).(maxFreq - minFreq)
to totalBeauty
.totalBeauty
.def beautySum(s):
total_beauty = 0
n = len(s)
for i in range(n):
count = [0] * 26
for j in range(i, n):
idx = ord(s[j]) - ord('a')
count[idx] += 1
freq_list = [c for c in count if c > 0]
max_freq = max(freq_list)
min_freq = min(freq_list)
total_beauty += (max_freq - min_freq)
return total_beauty
# Example
s = "aabcb"
print("Sum of Beauty:", beautySum(s))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(n^2) | We iterate through all possible substrings (n^2 combinations), and each frequency check takes constant time. |
Average Case | O(n^2) | The main loop processes all substrings, and frequency difference is computed in O(26) = O(1). |
Average Case | O(n^2) | Even if all characters are distinct, the double loop covers all substrings of the input string. |
O(1)
Explanation: Only a fixed-size array of 26 elements is used for frequency counting.
⬅ Previous Topic
Edit Distance ProblemNext Topic ⮕
Reverse Each Word in a String - Optimal ApproachYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.