Count Different Palindromic Subsequences
Hard
Topics
Given a string s, count the different non-empty palindromic subsequences it contains. Two subsequences are different when the strings they spell differ, so the same string reached by different positions counts once.
Return the count modulo 10^9 + 7.
Example 1
Input: s = "bccb" Output: 6 Explanation: The distinct palindromes are b, c, bb, cc, bcb and bccb. "b" counts once even though either of the two b positions could supply it, which is what "different" means here.
Example 2
Input: s = "abcd" Output: 4 Explanation: Only the four single characters are palindromes.
Example 3
Input: s = "aaa" Output: 3 Explanation: The distinct palindromes are a, aa and aaa — three, not seven, because identical strings collapse.
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
The word different is the entire difficulty. Counting palindromic subsequences by position is a short recurrence; counting them by the string they spell means that "aaa" contributes a, aa and aaa rather than seven, and every method has to avoid recounting the same string from different positions.
The way to make distinctness automatic is to organise the count by the outermost character. A palindrome inside s[i..j] that begins and ends with the letter c is determined by that letter plus a palindrome strictly inside the first and last occurrence of c in that range. Choosing the first and last occurrence rather than any pair is what removes the duplicates.
For a fixed range and a fixed letter c, let lo be the first position of c in the range and hi the last. If there is no c, it contributes nothing. If lo == hi, the only palindrome is c itself. Otherwise the contributions are c, cc, and c + any palindrome inside (lo, hi) + c.
Summing that over all 26 letters for every range gives the answer, and because each palindrome is attributed to exactly one letter and one range, nothing is double counted.
Approach
- Let
count(i, j)be the number of distinct non-empty palindromic subsequences ofs[i..j]. - For each of the 26 letters, find the first and last occurrence inside
[i, j]. - If the letter is absent, it adds nothing. If it occurs once, it adds 1, for the single character.
- Otherwise it adds
2 + count(lo + 1, hi - 1), for the single character, the doubled character, and each inner palindrome wrapped in that letter. - Sum over the letters, reduce modulo 10^9 + 7, and memoise by
(i, j). - Prefix tables of each letter’s next and previous occurrence make the first and last lookups constant time.
Walkthrough
s = "bccb"
count(0,3) over the letters present
letter b: first at 0, last at 3, different
contributes b, bb, and b + count(1,2) + b
count(1,2) is over "cc":
letter c: first 1, last 2, different
contributes c, cc, and c + count(2,1) + c
count(2,1) is an empty range -> 0
so count(1,2) = 2 { c, cc }
so b contributes 2 + 2 = 4 { b, bb, bcb, bccb }
letter c: first at 1, last at 2, different
contributes c, cc, and c + count(2,1)=0 + c
= 2 { c, cc }
total 4 + 2 = 6
and the six are: b, c, bb, cc, bcb, bccb
why first-and-last and not any pair
in "aaa", the pairs (0,1), (0,2), (1,2) would each
produce "aa". Fixing the outer letter to its FIRST
and LAST occurrence in the range makes "aa" arise
exactly once.Complexity
- Time — O(n^2 * 26): each of the n^2 ranges sums over the alphabet, with constant-time first and last lookups.
- Space — O(n^2): the memo table over ranges dominates. The recursion adds a call stack as deep as the range shrinks, so O(n) frames, which the n^2 table swallows — but say it out loud in an interview rather than leaving the stack unaccounted for.
Common Pitfalls
- Counting by position instead of by string, which overcounts badly:
"aaa"gives 7 rather than 3. - Pairing any two occurrences of the outer letter rather than the first and the last, which produces the same palindrome more than once.
- Forgetting that a letter occurring once still contributes the single character.
- Dropping the modulus inside the recursion and only applying it at the end.
- Treating the empty subsequence as a palindrome. The count is over non-empty ones.
Full Solution — all languages
class Solution:
def countPalindromicSubsequences(self, s):
from functools import lru_cache
MOD = 10 ** 9 + 7
n = len(s)
@lru_cache(maxsize=None)
def count(i, j):
if i > j:
return 0
total = 0
for c in set(s[i:j + 1]):
lo = s.index(c, i, j + 1)
hi = s.rindex(c, i, j + 1)
if lo == hi:
total += 1 # just "c"
else:
# "c", "cc", and c + (each inner palindrome) + c
total += 2 + count(lo + 1, hi - 1)
return total % MOD
return count(0, n - 1)import java.util.*;
class Solution {
public int countPalindromicSubsequences(String s) {
chars = s;
memo = new int[s.length() + 1][s.length() + 1];
for (int[] row : memo) Arrays.fill(row, -1);
return count(0, s.length() - 1);
}
private String chars;
private int[][] memo;
private int count(int i, int j) {
final int MOD = 1000000007;
if (i > j) return 0;
if (memo[i][j] != -1) return memo[i][j];
Set<Character> letters = new TreeSet<>();
for (int p = i; p <= j; p++) letters.add(chars.charAt(p));
long total = 0;
for (char c : letters) {
int lo = i, hi = j;
while (chars.charAt(lo) != c) lo++;
while (chars.charAt(hi) != c) hi--;
if (lo == hi) total += 1;
else total += 2 + count(lo + 1, hi - 1);
}
memo[i][j] = (int) (total % MOD);
return memo[i][j];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int countPalindromicSubsequences(string s) {
const int MOD = 1000000007;
int n = (int)s.size();
vector<vector<int>> memo(n + 1, vector<int>(n + 1, -1));
function<int(int, int)> count = [&](int i, int j) -> int {
if (i > j) return 0;
if (memo[i][j] != -1) return memo[i][j];
set<char> letters(s.begin() + i, s.begin() + j + 1);
long long total = 0;
for (char c : letters) {
int lo = i, hi = j;
while (s[lo] != c) lo++;
while (s[hi] != c) hi--;
if (lo == hi) total += 1;
else total += 2 + count(lo + 1, hi - 1);
}
memo[i][j] = (int)(total % MOD);
return memo[i][j];
};
return count(0, n - 1);
}
};/**
* @param {string} s
* @return {number}
*/ var countPalindromicSubsequences = function(s) {
const MOD = 1000000007;
const n = s.length;
const memo = new Map();
const count = (i, j) => {
if (i > j) return 0;
const key = i * (n + 1) + j;
if (memo.has(key)) return memo.get(key);
const letters = new Set();
for (let p = i; p <= j; p++) letters.add(s[p]);
let total = 0;
for (const c of letters) {
let lo = i, hi = j;
while (s[lo] !== c) lo++;
while (s[hi] !== c) hi--;
if (lo === hi) total += 1;
else total += 2 + count(lo + 1, hi - 1);
}
total %= MOD;
memo.set(key, total);
return total;
};
return count(0, n - 1);
};