Sum of beauty of all substrings

November 5, 2022

array-and-hashmap

Problem URL: Sum of beauty of all substrings

We will follow the problem statement, and solve the problem with a brute force approach.

class Solution:
    def beautySum(self, s: str) -> int:
        res = 0
        for i in range(len(s)-1):
            count = collections.defaultdict(int)
            count[s[i]] += 1

            for j in range(i+1, len(s)):
                count[s[j]] += 1
                res += max(count.values()) - min(count.values())

        return res

Time Complexity: O(n^2)
Space Complexity: O(n)