Skip to content

1930. Unique Length-3 Palindromic Subsequences 👍

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int countPalindromicSubsequence(string s) {
    int ans = 0;
    vector<int> first(26, s.length());
    vector<int> last(26);

    for (int i = 0; i < s.length(); ++i) {
      const int index = s[i] - 'a';
      first[index] = min(first[index], i);
      last[index] = i;
    }

    for (int i = 0; i < 26; ++i)
      if (first[i] < last[i])
        ans += unordered_set<int>(s.begin() + first[i] + 1, s.begin() + last[i])
                   .size();

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
  public int countPalindromicSubsequence(String s) {
    int ans = 0;
    int[] first = new int[26];
    int[] last = new int[26];

    Arrays.fill(first, s.length());

    for (int i = 0; i < s.length(); ++i) {
      final int index = s.charAt(i) - 'a';
      first[index] = Math.min(first[index], i);
      last[index] = i;
    }

    for (int i = 0; i < 26; ++i)
      if (first[i] < last[i])
        ans += s.substring(first[i] + 1, last[i]).chars().distinct().count();

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def countPalindromicSubsequence(self, s: str) -> int:
    ans = 0
    first = [len(s)] * 26
    last = [0] * 26

    for i, c in enumerate(s):
      index = string.ascii_lowercase.index(c)
      first[index] = min(first[index], i)
      last[index] = i

    for f, l in zip(first, last):
      if f < l:
        ans += len(set(s[f + 1:l]))

    return ans