Unique Length-3 Palindromic Subsequences — LeetCode 1930 Python Solution

MediumBit ManipulationHash TableStringPrefix Sum
Problem
#1930
Pattern
Prefix Sum
Reading time
2 min

The problem

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.

Example

Input
s = "aabca"
Output
3
Explanation
The 3 palindromic subsequences of length 3 are:

Python solution

Python
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

Complexity

MeasureComplexity
TimeO(n \times |\Sigma|), where n is the length of the string and \Sigma is the size of the character set
SpaceO(|\Sigma|) or O(1) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1930. Unique Length-3 Palindromic Subsequences is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.

The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1930. Unique Length-3 Palindromic Subsequences?
LeetCode 1930. Unique Length-3 Palindromic Subsequences is rated Medium on LeetCode.
What topics does LeetCode 1930. Unique Length-3 Palindromic Subsequences cover?
LeetCode 1930. Unique Length-3 Palindromic Subsequences is tagged Bit Manipulation, Hash Table, String and Prefix Sum on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview