Count Palindromic Subsequences - Problem
Count Palindromic Subsequences
Given a string of digits
A palindrome reads the same forwards and backwards (like "12321" or "90509"). A subsequence is formed by deleting some characters from the original string while maintaining the relative order of remaining characters.
Example: In string "12321", one valid 5-length palindromic subsequence could be the entire string itself, but there might be others depending on repeated digits.
Since palindromic subsequences can grow exponentially with string length, we return the result modulo
Given a string of digits
s, your task is to find all palindromic subsequences of exactly length 5 and return their count modulo 109 + 7.A palindrome reads the same forwards and backwards (like "12321" or "90509"). A subsequence is formed by deleting some characters from the original string while maintaining the relative order of remaining characters.
Example: In string "12321", one valid 5-length palindromic subsequence could be the entire string itself, but there might be others depending on repeated digits.
Since palindromic subsequences can grow exponentially with string length, we return the result modulo
109 + 7 to keep numbers manageable. Input & Output
example_1.py — Basic Case
$
Input:
s = "103301"
›
Output:
2
💡 Note:
The palindromic subsequences of length 5 are "10301" and "13031". Both read the same forwards and backwards.
example_2.py — All Same Digits
$
Input:
s = "1111111"
›
Output:
21
💡 Note:
We need to choose 5 positions from 7 available positions, all containing '1'. This gives us C(7,5) = 21 palindromic subsequences.
example_3.py — Minimum Length
$
Input:
s = "12321"
›
Output:
1
💡 Note:
With exactly 5 characters forming a palindrome, there's only one way to select all 5 positions, giving us the palindrome "12321".
Constraints
- 1 ≤ s.length ≤ 103
- s consists of digits only (0-9)
- Result must be returned modulo 109 + 7
- We only count palindromic subsequences of exactly length 5
Visualization
Tap to expand
Understanding the Visualization
1
Identify Structure
5-length palindromes have form ABCBA where A matches A and B matches B
2
Fix Center
Choose each character position as the middle (C) of the palindrome
3
Count Pairs
For each outer character, count valid middle character pairs
4
Combine Results
Multiply the number of ways to choose each pair type
Key Takeaway
🎯 Key Insight: By recognizing the ABCBA structure and fixing the center, we can efficiently count palindromes using combinatorics rather than generating all subsequences.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code