Approach
[Translate by ChatGPT]
The task is to find all palindromic subsequences of length 3. My first intuition was that we only need to count possibilities, because with length 3 the first and last characters must be the same.
Initially, I thought about scanning twice and maintaining counts for the prefix (0 → i) and suffix (i → end). However, that would require a 26 × n array. Later I realized I only needed to maintain one side, and update the other side while computing the answer, which reduces the space to just 26. This actually feels similar to the time–space trade-off mindset in hardware design.
Finally, I noticed the problem only cares about unique strings, so each palindrome should be counted once. I ended up using a bitmap for each position, which gives an O(1) space solution.
Code
class Solution {
public:
int countPalindromicSubsequence(string s) {
vector<int> front(26,0); // number of char in 0~i
vector<int> back(26,0); // number of char in i~end
for(const auto& c: s) {
++back[c-'a'];
}
vector<int> ansAry(26,0); // center char map to bit code
for(const auto& c: s) {
--back[c-'a']; // number of char in i+1~end
for(int i = 0 ; i < 26 ; ++i) {
if(front[i] > 0 && back[i] > 0) {
ansAry[c-'a'] |= (1 << i);
}
}
++front[c-'a']; // update front
}
int ans = 0;
for(int i = 0 ; i < 26 ; ++i) {
for(int j = 0 ; j < 26 ; ++j) {
if ( (ansAry[i] & (1 << j)) != 0 ) {
++ans;
}
}
}
return ans;
}
};