array and hashmap October 8, 2022

Unique length 3 palindromic subsequences

Time O(n) Space O(n) Open original problem

For each palindromes in format of "aba", we enumerate the character on two side. We find its first occurrence and its last occurrence, all the characters in the middle are the candidate for the middle char.

class Solution:
    def countPalindromicSubsequence(self, s: str) -> int:
        res = 0
        for c in string.ascii_lowercase:
            i, j = s.find(c), s.rfind(c)
            if i > -1:
                res += len(set(s[i + 1: j]))
        return res

Time Complexity: O(n)
Space Complexity: O(n)