The Count Different Palindromic Subsequences coding problem asks you to find the number of unique non-empty palindromic subsequences in a string. Since the same subsequence can be formed in multiple ways, you only count distinct ones. You need to return the answer modulo 10^9 + 7.
This is a "Hard" Dynamic Programming interview pattern asked by Uber and LinkedIn. It tests your ability to handle 2D DP and de-duplication logic. It evaluates whether you can define a state that accounts for different characters at the boundaries of the string and how they contribute to new palindromes.
The problem uses 2D Dynamic Programming.
dp[i][j] be the number of distinct palindromic subsequences in s[i..j].s[i] != s[j], dp[i][j] = dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1].s[i] == s[j], it gets more complex. Any palindrome in s[i+1..j-1] can be wrapped by s[i] and s[j] to form a new one. You also need to subtract duplicates based on how many times s[i] appears inside the inner substring.s = "bccb"
b, c, c, b. (Distinct: b, c).cc, bb, bc, cb (Wait, only palindromes). cc, bb.c: 1cc: 2 (c, cc)bcc: 3 (b, c, cc)bccb: The b...b wrap adds new palindromes.
This requires careful calculation of the "inner" occurrences of the boundary character.dp[i+1][j-1]. Always use (a - b + MOD) % MOD.For "distinct subsequence" problems, the state usually needs to track where the first and last occurrences of a character are. Precalculating these positions can turn an O(N^3) DP into O(N^2).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Stepping Numbers in Range | Hard | Solve | |
| Distinct Subsequences | Hard | Solve | |
| Distinct Subsequences II | Hard | Solve | |
| Strange Printer | Hard | Solve | |
| Valid Palindrome III | Hard | Solve |