MediumNo. 1930

Unique Length-3 Palindromic Subsequences — LeetCode 1930 Python Solution

Pattern
Prefix Sum
Topics
Bit Manipulation, Hash Table, String, 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

PythonSolution
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

Time
O(n × |Σ|), where n is the length of the string and Σ is the size of the character set
Space · auxiliary
O(|Σ|) or O(1)

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.

Free to download. Check it runs on your machine, then pick a plan.