#2262

Total Appeal of A String

Hard
Hash TableStringDynamic ProgrammingHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

The optimal solution leverages the last occurrence of each character to efficiently calculate the contribution of each character to the total appeal. By tracking the last seen index of each character, we can determine how many substrings end with that character and contribute to the appeal.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a variable to track the total appeal and a map to store the last occurrence of each character.
  2. 2Step 2: Iterate through the string, and for each character, calculate its contribution based on its last occurrence.
  3. 3Step 3: Update the last occurrence of the character and sum the contributions to the total appeal.
solution.py14 lines
1# Full working Python code
2
3def total_appeal(s):
4    total = 0
5    last_occurrence = {}
6    n = len(s)
7    for i in range(n):
8        char = s[i]
9        last_index = last_occurrence.get(char, -1)
10        total += (i - last_index) * (n - i)
11        last_occurrence[char] = i
12    return total
13
14print(total_appeal('abbca'))  # Output: 28

Complexity note: The time complexity is O(n) because we traverse the string once, and each character's contribution is calculated in constant time. The space complexity is O(n) due to the storage of the last occurrence of characters.

  • 1Understanding how the last occurrence of characters affects substring contributions is crucial.
  • 2Using a map to track last occurrences allows for efficient calculations without generating all substrings.

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