# 1930. Unique Length-3 Palindromic Subsequences

```
T: O(n + 26n)
S: O(26)
```

````java

```java
class Solution {
    public int countPalindromicSubsequence(String s) {
        int[] firstOccur = new int[26];
        int[] lastOccur = new int[26];
        Arrays.fill(firstOccur, -1);

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (firstOccur[c - 'a'] == -1) {
                firstOccur[c - 'a'] = i;
            }
            lastOccur[c - 'a'] = i;
        }

        int result = 0;
        Set<Character> countSet = new HashSet<>();
        for (int i = 0; i < 26; i++) {
            if (firstOccur[i] != -1 && lastOccur[i] != -1) {
                countSet = new HashSet<>();
                for (int j = firstOccur[i]+1; j < lastOccur[i]; j++) {
                    countSet.add(s.charAt(j));
                }
                result += countSet.size();
            }
        }
        return result;
    }
}

/**

T: O(n + 26n)
S: O(26)

first[] record smallest index of String s's char

why Arrays.fill(firstOccur, -1);
because we only want ""first"" occur, so if it's -1, it's the first one char in index


last[] record largest index...

i = 0 ~ 25
then cal between first[i] and last[i]
how many distinct char there

sum them all, it's the ans

ex: 
because we ask for len 3 palindrom... so first and third must be the same, then we only need to cal between 
these first and third, how many distinct char 


aabca

  abc -> 3 different char  
a     a

and we can find another pair (first and third) is the same, so...
ans = 3

-> ex: this is cal between a and a, there are how many distinct char
for (int j = firstOccur[i]+1; j < lastOccur[i]; j++) {

 */
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/weekly-contest/1930.-unique-length-3-palindromic-subsequences.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
