Leetcode Problem 1781. Sum of Beauty of All Substrings

1781. Sum of Beauty of All Substrings

Leetcode Solutions

Iterative Substring Frequency Count

  1. Initialize a variable total_beauty to store the sum of beauties of all substrings.
  2. Iterate over the string with two nested loops, with the outer loop index i representing the start of the substring and the inner loop index j representing the end of the substring.
  3. For each new starting index i, initialize a frequency array freq of size 26 to 0 (for 26 lowercase English letters).
  4. For each j from i to the end of the string, increment the frequency of the character s[j] in the freq array.
  5. After each increment, calculate the current substring's beauty by finding the maximum and minimum non-zero frequencies in the freq array.
  6. Add the beauty to total_beauty.
  7. After the inner loop ends, move to the next starting index i and repeat steps 3-6.
  8. Return total_beauty as the final result.
UML Thumbnail

HashMap Based Substring Frequency Count

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Code Diffs Compare
Full Screen
Copy Answer Code
Loading...