Skip to content

2262. Total Appeal of A String 👍

Approach 1: DP

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  long long appealSum(string s) {
    long long ans = 0;
    int dp = 0;  // # of appeal of string ending at current index
    vector<int> lastOccurrence(26, -1);

    for (int i = 0; i < s.length(); ++i) {
      dp += i - lastOccurrence[s[i] - 'a'];
      ans += dp;
      lastOccurrence[s[i] - 'a'] = i;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public long appealSum(String s) {
    long ans = 0;
    int dp = 0; // # of appeal of string ending at current index
    int[] lastOccurrence = new int[26];
    Arrays.fill(lastOccurrence, -1);

    for (int i = 0; i < s.length(); ++i) {
      dp += i - lastOccurrence[s.charAt(i) - 'a'];
      ans += dp;
      lastOccurrence[s.charAt(i) - 'a'] = i;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def appealSum(self, s: str) -> int:
    ans = 0
    dp = 0  # # Of appeal of ending at current index
    lastOccurrence = [-1] * 26

    for i, c in enumerate(s):
      dp += i - lastOccurrence[ord(c) - ord('a')]
      ans += dp
      lastOccurrence[ord(c) - ord('a')] = i

    return ans

Approach 2: Combinatorics

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  long long appealSum(string s) {
    long long ans = 0;
    vector<int> lastOccurrence(26, -1);

    for (int i = 0; i < s.length(); ++i) {
      ans += (i - lastOccurrence[s[i] - 'a']) * (s.length() - i);
      lastOccurrence[s[i] - 'a'] = i;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long appealSum(String s) {
    long ans = 0;
    int[] lastOccurrence = new int[26];
    Arrays.fill(lastOccurrence, -1);

    for (int i = 0; i < s.length(); ++i) {
      ans += (i - lastOccurrence[s.charAt(i) - 'a']) * (s.length() - i);
      lastOccurrence[s.charAt(i) - 'a'] = i;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def appealSum(self, s: str) -> int:
    ans = 0
    lastOccurrence = [-1] * 26

    for i, c in enumerate(s):
      ans += (i - lastOccurrence[ord(c) - ord('a')]) * (len(s) - i)
      lastOccurrence[ord(c) - ord('a')] = i

    return ans