Unique Length-3 Palindromic Subsequences Problem
Description
LeetCode Problem 1930.
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
- For example,
"ace"is a subsequence of"abcde".
Example 1:
Input: s = "aabca"
Output: 3
Explanation: The 3 palindromic subsequences of length 3 are:
- "aba" (subsequence of "aabca")
- "aaa" (subsequence of "aabca")
- "aca" (subsequence of "aabca")
Example 2:
Input: s = "adc"
Output: 0
Explanation: There are no palindromic subsequences of length 3 in "adc".
Example 3:
Input: s = "bbcbaba"
Output: 4
Explanation: The 4 palindromic subsequences of length 3 are:
- "bbb" (subsequence of "bbcbaba")
- "bcb" (subsequence of "bbcbaba")
- "bab" (subsequence of "bbcbaba")
- "aba" (subsequence of "bbcbaba")
Constraints:
3 <= s.length <= 10^5sconsists of only lowercase English letters.
Solution
Approach: Enumerate the End Letter
A palindrome of length three looks like c x c. There are only 26 choices for the end letter c, so try each one.
For letter c, find its first position l and its last position r in s. The best chance to fit a middle letter between two copies of c is to use these two outermost ones. If r - l > 1, every distinct letter strictly between l and r gives one different palindrome c x c, so add the number of distinct letters in s[l + 1 .. r - 1] to the answer.
Complexity: O(26 * n) time and O(26) extra space, where n is the length of s.
from string import ascii_lowercase
class Solution:
def countPalindromicSubsequence(self, s: str) -> int:
ans = 0
for c in ascii_lowercase:
l, r = s.find(c), s.rfind(c)
if r - l > 1:
ans += len(set(s[l + 1 : r]))
return ans