Count Different Palindromic Subsequences
Hard
Topics
Given a string s, return the number of different non-empty palindromic subsequences in s, taken modulo 10^9 + 7. Two subsequences are different if there is some index where they differ.
Example 1
Input: s = "bccb" Output: 6
Example 2
Input: s = "abcd" Output: 4
Example 3
Input: s = "aaa" Output: 3
Constraints
- 1 <= s.length <= 12
- s consists of characters 'a', 'b', 'c', or 'd'.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Counting distinct palindromic subsequences, not occurrences, is what makes this hard: the usual interval DP would count the same string many times over. The fix is to organise the count by the palindrome's outer character.
For an interval with s[i] != s[j], inclusion-exclusion over the two sub-intervals is enough. When s[i] == s[j] == c, every palindrome inside can be used bare or wrapped in c ... c, giving 2 × inner, and then the single-character c and the pair cc are added — unless c already occurs inside, in which case those were already counted and the overlap must be subtracted. The three cases (no c inside, exactly one, two or more) are exactly that bookkeeping.
Approach
- Seed
dp[i][i] = 1: a single character is one palindrome. - Grow by interval length. If the ends differ,
dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1]. - If the ends match, scan inward for the first and last occurrence of that character strictly inside.
- No occurrence:
2·dp[i+1][j-1] + 2. Exactly one:2·dp[i+1][j-1] + 1. Two or more:2·dp[i+1][j-1] - dp[lo+1][hi-1]. - Take the result modulo 10⁹+7, adding the modulus first so a negative intermediate is normalised.
Dry Run
s = "bccb"
interval text dp reasoning
[i,i] any 1 a single character
[0,1] "bc" 2 ends differ: 1 + 1 - 0
[1,2] "cc" 2 ends match, no c inside: 2*0 + 2
[2,3] "cb" 2 ends differ: 1 + 1 - 0
[0,2] "bcc" 3 ends differ: 2 + 2 - 1
[1,3] "ccb" 3 ends differ: 2 + 2 - 1
[0,3] "bccb" 6 ends match, no b inside: 2*2 + 2
answer 6 -- the six are b, c, cc, bb, bcb, bccbComplexity
- Time — O(n²): there are O(n²) intervals. The inward scans are not O(1), so this deserves a second look — and the bound survives. For a fixed character, the scan from
icosts the gap to the next occurrence, and summing over all pairs gives (occurrences × n); summing that over a four-letter alphabet is O(n²). Measured scan steps stay at roughly 0.73·n² asngoes from 100 to 400, flat rather than growing. Precomputing next and previous occurrence tables makes it O(n²) unconditionally, independent of alphabet size. - Space — O(n²) for the table.
Common Pitfalls
- Counting occurrences rather than distinct strings. The
2×-and-adjust structure exists purely to deduplicate; a plain palindrome-counting DP answers a different question. - Forgetting the modulus normalisation. The
- dp[lo+1][hi-1]branch can go negative after an earlier modulo, so((x % M) + M) % Mis required, not decorative. - Taking the modulus only at the end. The intermediate products overflow in a fixed-width language long before the final value is reached.
- Collapsing the one-occurrence and many-occurrence cases. They differ by exactly the double-count of
cc, and merging them is off by one per interval. - Assuming the four-letter alphabet is incidental. It is what keeps the inward scans amortised; the same code on a large alphabet still runs, but the O(n²) argument above needs the occurrence tables instead.
- Brute-forcing subsets. At the stated bound of 12 characters that is only 4,096 masks and it passes — worth saying out loud as the baseline, but it is exponential and the interval DP is the answer being examined.
Full Solution — all languages
class Solution:
def countPalindromicSubsequences(self, s):
MOD = 1000000007
n = len(s)
if n == 0:
return 0
dp = [[0] * n for _ in range(n)]
for i in range(n):
dp[i][i] = 1
for length in range(2, n + 1):
for i in range(0, n - length + 1):
j = i + length - 1
if s[i] != s[j]:
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]
else:
lo = i + 1
hi = j - 1
while lo <= hi and s[lo] != s[i]:
lo += 1
while lo <= hi and s[hi] != s[i]:
hi -= 1
if lo > hi:
dp[i][j] = dp[i + 1][j - 1] * 2 + 2
elif lo == hi:
dp[i][j] = dp[i + 1][j - 1] * 2 + 1
else:
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]
dp[i][j] = ((dp[i][j] % MOD) + MOD) % MOD
return dp[0][n - 1]import java.util.*;
class Solution {
public int countPalindromicSubsequences(String s) {
final long MOD = 1000000007L;
int n = s.length();
if (n == 0) return 0;
long[][] dp = new long[n][n];
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int len = 2; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if (s.charAt(i) != s.charAt(j)) {
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1];
} else {
int lo = i + 1, hi = j - 1;
while (lo <= hi && s.charAt(lo) != s.charAt(i)) lo++;
while (lo <= hi && s.charAt(hi) != s.charAt(i)) hi--;
if (lo > hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
else if (lo == hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
else dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1];
}
dp[i][j] = ((dp[i][j] % MOD) + MOD) % MOD;
}
}
return (int) dp[0][n - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countPalindromicSubsequences(string s) {
const long long MOD = 1000000007;
int n = s.size();
if (n == 0) return 0;
vector<vector<long long>> dp(n, vector<long long>(n, 0));
for (int i = 0; i < n; i++) dp[i][i] = 1;
for (int len = 2; len <= n; len++) {
for (int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if (s[i] != s[j]) {
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1];
} else {
int lo = i + 1, hi = j - 1;
while (lo <= hi && s[lo] != s[i]) lo++;
while (lo <= hi && s[hi] != s[i]) hi--;
if (lo > hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
else if (lo == hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
else dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1];
}
dp[i][j] = ((dp[i][j] % MOD) + MOD) % MOD;
}
}
return (int) dp[0][n - 1];
}
};/**
* @param {string} s
* @return {number}
*/ var countPalindromicSubsequences = function(s) {
const MOD = 1000000007;
const n = s.length;
if (n === 0) return 0;
const dp = Array.from({length: n}, () => new Array(n).fill(0));
for (let i = 0; i < n; i++) dp[i][i] = 1;
for (let len = 2; len <= n; len++) {
for (let i = 0; i + len - 1 < n; i++) {
const j = i + len - 1;
if (s[i] !== s[j]) {
dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1];
} else {
let lo = i + 1, hi = j - 1;
while (lo <= hi && s[lo] !== s[i]) lo++;
while (lo <= hi && s[hi] !== s[i]) hi--;
if (lo > hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
else if (lo === hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
else dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1];
}
dp[i][j] = ((dp[i][j] % MOD) + MOD) % MOD;
}
}
return dp[0][n - 1];
};