Number of palindromic subsequences of length k where k <= 3
Given a string S of length n and a positive integer k. The task is to find number of Palindromic Subsequences of length k where k <= 3.
Input : s = "aabab", k = 2 Output : 4
Input : s = "aaa", k = 3 Output : 1
For k = 1, we can easily say that number of characters in string will be the answer.
For k = 2, we can easily make pairs of same characters so we have to maintain the count of each character in string and then calculate
sum = 0 for character 'a' to 'z' cnt = count(character) sum = sum + cnt*(cnt-1)/2 sum is the answer.
Now as k increases, it became difficult to find. How to find the answer for k = 3 ? So the idea is to see that palindromes of length 3 will be of the format TZT, so we have to maintain two matrices, one to calculate the prefix sum of each character, and one to calculate suffix sum of each character in the string.
Prefix sum for a character T at index i is L[T][i] i.e number of times T has occurred in the range [0, i](indices).
Suffix sum for a character T at index i is R[T][i] has occurred in the range [i, n – 1](indices).
Both the matrices will be 26*n and one can precompute both these matrices in complexity O(26*n) where n is the length of the string.
Now how to compute the subsequence? Think over this: for an index i suppose a character X appears n1 times in the range [0, i – 1] and n2 times in the range [i + 1, n – 1] then the answer for this character will be n1 * n2 i.e L[X][i-1] * R[X][i + 1], this will give the count of subsequences of the format X-s[i]-X where s[i] is the character at i-th index. So for every index i you will have to count the product of
L[X][i-1] * R[X][i+1], where i is the range [1, n-2] and X will be from 'a' to 'z'
Below is the implementation of this approach: