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:
4
💡 Note:
The palindromes are: "bab" (b at positions 0,4,7), "bcb" (b at 0,1,7), "bab" (b at 1,4,7), "aca" (a at 2,5,6). Some have multiple ways to form but count as 1 unique palindrome.
Constraints
- 3 ≤ s.length ≤ 105
- s consists of only lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with characters that may repeat
2
Pattern
Find ABA patterns where A appears at least twice
3
Output
Count of unique 3-character palindromes
Key Takeaway
🎯 Key Insight: For each character that appears at least twice, count unique middle characters between its first and last occurrence
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code