Unique Length-3 Palindromic Subsequences — LeetCode 1930 Python Solution
- Problem
- #1930
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times |\Sigma|), where n is the length of the string and \Sigma is the size of the character set |
| Space | O(|\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.