Program to find sum of beauty of all substrings in Python


Suppose we have a string s. We have to find the sum of beauty of all of its substrings. The beauty of a string is actually the difference in frequencies between the most frequent and least frequent characters. So if the string is "abaacc", then its frequency is 3 - 1 = 2.

So, if the input is like s = "xxyzy", then the output will be 5 because the substrings with non-zero beauty are ["xxy","xxyz","xxyzy","xyzy","yzy"], each has beauty value 1.

To solve this, we will follow these steps −

  • res:= 0

  • for i in range 0 to size of s - 1, do

    • for j in range i+2 to size of s - 1, do

      • c:= a map containing characters frequency of substring of s from index i to j

      • v:= list of all frequency values of c

      • res := res +(maximum of v - minimum of v)

  • return res

Example

Let us see the following implementation to get better understanding −

from collections import Counter

def solve(s):
   res=0
   for i in range(len(s)):
      for j in range(i+2,len(s)):
         c=Counter(s[i:j+1])
         v=c.values()
         res+=(max(v)-min(v))
   return res

s = "xxyzy"
print(solve(s))

Input

"xxyzy"

Output

5

Updated on: 06-Oct-2021

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements