Problem 730 · LeetCode 730(opens in a new tab)
Count Different Palindromic Subsequences
HardDynamic programming
You are given a string s made only of the letters a, b, c and d. A subsequence is what is left after deleting any number of letters (possibly none) while keeping the order of the rest. A palindrome reads the same forwards and backwards.
Return how many different non-empty palindromic subsequences s has. Two subsequences that spell the same text count once, no matter which positions they come from. The count can be huge, so return it modulo 1,000,000,007.
Example 1
Input: s = "abcb" Output: 5 Why: the palindromes are a, b, c, bb and bcb
2 more examples and the constraints
Example 2
Input: s = "aaaa" Output: 4 Why: a, aa, aaa and aaaa; many position choices, only 4 texts
Example 3
Input: s = "dacad" Output: 10 Why: a, c, d, aa, dd, aca, dad, dcd, daad and dacad
Constraints
- 1 ≤ s.length ≤ 1,000
- Every character of
sis one ofa,b,c,d
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Interval DP per end letterO(4·n²)
- One table with next/previous letterO(n²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 1,000 letters | Verdict |
|---|---|---|---|
| Interval DP per end letter | O(4·n²) | Clear cases; four tables | |
| One table with next/previous | O(n²) | Best; one table |
n = length of s; 4 = size of the alphabet.
Edge cases to test
- One letter. "c" has exactly one palindrome.
- All the same letter. "aaaa" gives 4: one text per length, however many ways to pick positions.
- No repeated letter. "abcd" gives 4: only the single letters.
- Large answers. Long strings overflow fast; take the remainder after every cell and fix negatives.
- Matching letters deep inside. "abaaba"-style strings hit the subtract case; test them.
Common mistakes
- Counting subsequences by position instead of by text, so "aa" from different positions is counted twice.
- Forgetting the overlap term when the ends differ, which counts the middle twice.
- Letting a subtraction under the modulus go negative and returning a negative number.
How to talk through it
- 1Clarify. Distinct by text, not by position? Only four letters? Answer modulo 1,000,000,007?
- 2Rule out brute force. 2ⁿ subsequences for n = 1,000 is impossible; we must count, not list.
- 3Set up the interval DP. dp[i][j] from shorter ranges; ends differ means inclusion–exclusion.
- 4Handle matching ends. Wrap the inner palindromes, then +2, +1 or subtract the repeated middle by how many matches lie inside.
- 5Test out loud. Run "abcb", "aaaa" and a string with three of the same letter before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?