#1781

Sum of Beauty of All Substrings

Medium
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(1)
💡

Intuition

Time O(n²)Space O(1)

The optimal solution uses a sliding window approach combined with a frequency count to efficiently calculate the beauty of all substrings without generating them explicitly. This reduces redundant calculations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a frequency array to count character occurrences.
  2. 2Step 2: Use two pointers to define the current substring window.
  3. 3Step 3: For each window, update the frequency array and calculate the beauty by finding the max and min frequencies.
  4. 4Step 4: Sum the beauties for all valid substrings.
solution.py14 lines
1def beautySum(s):
2    total_beauty = 0
3    n = len(s)
4    for i in range(n):
5        freq = [0] * 26
6        max_freq = 0
7        min_freq = float('inf')
8        for j in range(i, n):
9            freq[ord(s[j]) - ord('a')] += 1
10            max_freq = max(max_freq, freq[ord(s[j]) - ord('a')])
11            min_freq = min(min_freq, freq[ord(s[j]) - ord('a')]) if freq[ord(s[j]) - ord('a')] > 0 else min_freq
12            if min_freq != float('inf'):
13                total_beauty += max_freq - min_freq
14    return total_beauty

Complexity note: The time complexity remains O(n²) due to the nested loops for substrings, but we optimize the beauty calculation using a frequency array. The space complexity is O(1) since the frequency array size is constant (26 for lowercase letters).

  • 1The beauty of a substring is determined by the frequency of characters.
  • 2Using frequency arrays can optimize the calculation of max and min frequencies.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.