Unique Length-3 Palindromic Subsequences - Problem
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
Input & Output
Example 1 — Basic Case
$
Input:
s = "aabca"
›
Output:
3
💡 Note:
The 3 palindromic subsequences of length 3 are: "aaa" (using s[0], s[1], s[4]), "aba" (using s[0], s[2], s[4]), and "aca" (using s[0], s[3], s[4]). Note that "aaa" uses the first two 'a's and the last 'a'.
Example 2 — No Palindromes
$
Input:
s = "abc"
›
Output:
0
💡 Note:
There are no characters that appear more than once, so no palindromic subsequences of length 3 can be formed.
Example 3 — Multiple Occurrences
$
Input:
s = "bbcacaba"
›
Output:
6
💡 Note:
The palindromes are: For 'b' (positions 0,1,6,7): 'bab', 'bcb', 'bbb' using middle chars {a,b,c}. For 'c' (positions 2,4): 'cac' using middle char {a}. For 'a' (positions 3,5,6): 'aca', 'aaa' using middle chars {c,a}. Total: 3+1+2=6 unique palindromes.
Constraints
- 3 ≤ s.length ≤ 105
- s consists of only lowercase English letters
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code