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
Count Palindromic Subsequences (Length 5) INPUT String s = "103301" 1 i=0 0 i=1 3 i=2 3 i=3 0 i=4 1 i=5 Palindrome Structure: a b c b a Pattern: abcba (mirror) Valid Subsequence: 1 0 3 0 1 "10301" is palindrome ALGORITHM STEPS 1 Build Prefix Counts Count pairs (a,b) before each position 2 Build Suffix Counts Count pairs (b,a) after each position 3 Iterate Middle (c) For each middle char, combine prefix/suffix 4 Sum Products prefix[a][b] * suffix[b][a] for all digit pairs Pair Counting prefix[1][0] = 1 suffix[0][1] = 1 mid='3': 1*1 = 1 FINAL RESULT Found Palindromic Subsequences: "10301" Indices: [0, 1, 2, 4, 5] Verification: 1 = 1 (OK) 0 = 0 (OK) 3 = center Output: 1 mod 10^9 + 7 Key Insight: For 5-char palindrome "abcba": precompute prefix counts of (a,b) pairs BEFORE middle position, and suffix counts of (b,a) pairs AFTER middle. For each middle char 'c', multiply matching pairs. Time: O(n * 100) = O(n), Space: O(100) = O(1) for 10 digits. Avoids O(n^5) brute force! TutorialsPoint - Count Palindromic Subsequences | Optimized DP - Prefix/Suffix Counting
Asked in
Google 25 Amazon 18 Microsoft 15
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen