Count Palindromic Subsequences - Problem
Given a string of digits s, return the number of palindromic subsequences of s having length 5. Since the answer may be very large, return it modulo 109 + 7.
Note:
- A string is palindromic if it reads the same forward and backward.
- A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Input & Output
Example 1 — Basic Case
$
Input:
s = "103301"
›
Output:
1
💡 Note:
The palindromic subsequence of length 5 is "10301". We take positions 0,1,2,4,5 to get digits 1,0,3,0,1 which forms a palindrome.
Example 2 — Multiple Palindromes
$
Input:
s = "1212121"
›
Output:
6
💡 Note:
Multiple 5-digit palindromic subsequences exist: 12121 can be formed in 6 different ways by choosing different positions of 1s and 2s.
Example 3 — No Valid Palindromes
$
Input:
s = "12345"
›
Output:
0
💡 Note:
No palindromic subsequences of length 5 can be formed since all digits are different.
Constraints
- 1 ≤ s.length ≤ 1000
- s consists only of digits.
Visualization
Tap to expand
Understanding the Visualization
1
Input String
String of digits with potential palindromic subsequences
2
Pattern Recognition
Find positions where palindrome pattern abcba exists
3
Count Result
Total number of valid 5-digit palindromic subsequences
Key Takeaway
🎯 Key Insight: Look for matching pairs of digits that can form the outer and inner layers of a 5-digit palindrome pattern
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code