Count Palindromic Subsequences Problem
Description
LeetCode Problem 2484.
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 10^9 + 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.
Example 1:
Input: s = "103301"
Output: 2
Explanation:
There are 6 possible subsequences of length 5: "10330","10331","10301","10301","13301","03301".
Two of them (both equal to "10301") are palindromic.
Example 2:
Input: s = "0000000"
Output: 21
Explanation: All 21 subsequences are "00000", which is palindromic.
Example 3:
Input: s = "9999900000"
Output: 2
Explanation: The only two palindromic subsequences are "99999" and "00000".
Constraints:
1 <= s.length <= 10^4sconsists of digits.
Solution
Approach: Prefix and Suffix Pair Counts
A palindrome of length 5 has the form a b c b a. Fix the middle digit at position i. The outer part is then a pair of digits (a, b) that occurs in this order (a before b) among the digits to the left of i, and the same two digits in the order b, a among the digits to the right, which is the same as the pair (a, b) read from the right end.
Precompute pre[i][a][b], the number of index pairs p < q among the first i digits with digits a and b, and suf[i][a][b] for the pairs counted from the right end in the part from i on, using running counts of each digit. Then, for each middle i, the number of palindromes is the sum over all 100 digit pairs of pre[i-1][a][b] * suf[i+1][a][b]. Add up all middles modulo 10^9 + 7.
Complexity: O(100 * n) time and O(100 * n) space, where n is the length of s.
class Solution:
def countPalindromes(self, s: str) -> int:
mod = 10**9 + 7
n = len(s)
pre = [[[0] * 10 for _ in range(10)] for _ in range(n + 2)]
suf = [[[0] * 10 for _ in range(10)] for _ in range(n + 2)]
t = list(map(int, s))
c = [0] * 10
for i, v in enumerate(t, 1):
for j in range(10):
for k in range(10):
pre[i][j][k] = pre[i - 1][j][k]
for j in range(10):
pre[i][j][v] += c[j]
c[v] += 1
c = [0] * 10
for i in range(n, 0, -1):
v = t[i - 1]
for j in range(10):
for k in range(10):
suf[i][j][k] = suf[i + 1][j][k]
for j in range(10):
suf[i][j][v] += c[j]
c[v] += 1
ans = 0
for i in range(1, n + 1):
for j in range(10):
for k in range(10):
ans += pre[i - 1][j][k] * suf[i + 1][j][k]
ans %= mod
return ans