Unique Length-3 Palindromic Subsequences - Problem
You're given a string s and need to find the count of unique palindromes of length 3 that can be formed as subsequences.
A palindrome reads the same forwards and backwards (like "aba" or "cdc"). A subsequence maintains the original character order but allows skipping characters.
Key points:
- We only count unique palindromes - duplicates count as one
- Length must be exactly 3
- Characters don't need to be consecutive in the original string
Example: In "aabca", we can form subsequences like "aba" and "aca", giving us 2 unique length-3 palindromes.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aabca"
โบ
Output:
3
๐ก Note:
The unique palindromes are: 'aaa' (using positions 0,1,4), 'aba' (using positions 0,2,4), and 'aca' (using positions 0,3,4). All use 'a' as outer characters with different middle characters.
example_2.py โ Single Character
$
Input:
s = "aaa"
โบ
Output:
1
๐ก Note:
Only one unique palindrome 'aaa' can be formed. Even though there are multiple ways to choose 3 'a's from the string, they all result in the same palindrome.
example_3.py โ No Repeated Characters
$
Input:
s = "abc"
โบ
Output:
0
๐ก Note:
No character appears more than once, so no 3-character palindromes can be formed since we need at least 2 occurrences of the same character for the first and last positions.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Bread Types
Scan string to find which characters appear at least twice (can be outer chars)
2
Find Sandwich Boundaries
For each 'bread' character, find its leftmost and rightmost positions
3
Count Filling Options
Between boundaries, count how many different 'filling' characters exist
4
Sum All Sandwiches
Each bread-filling combination creates a unique palindrome sandwich
Key Takeaway
๐ฏ Key Insight: Every 3-char palindrome is like a sandwich - identical 'bread' (outer chars) with any 'filling' (middle char) between the first and last occurrence of the bread character!
Time & Space Complexity
Time Complexity
O(n)
Single pass through string, set operations are O(1) average case
โ Linear Growth
Space Complexity
O(1)
Only storing at most 26 characters and their middle character sets
โ Linear Space
Constraints
- 3 โค s.length โค 105
- s consists of only lowercase English letters
- A palindrome must have exactly 3 characters
- Only unique palindromes are counted
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code