Remove Palindromic Subsequences — LeetCode 1332 Python Solution
EasyTwo PointersString
- Problem
- #1332
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a string s consisting only of letters 'a' and 'b'. In a single step you can remove one palindromic subsequence from s.
Example
- Input
- s = "ababa"
- Output
- 1
- Explanation
- s is already a palindrome, so its entirety can be removed in a single step.
Python solution
Python
class Solution:
def removePalindromeSub(self, s: str) -> int:
return 1 if s[::-1] == s else 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1332. Remove Palindromic Subsequences is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1332. Remove Palindromic Subsequences?
- LeetCode 1332. Remove Palindromic Subsequences is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1332. Remove Palindromic Subsequences?
- The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 1332. Remove Palindromic Subsequences?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1332. Remove Palindromic Subsequences cover?
- LeetCode 1332. Remove Palindromic Subsequences is tagged Two Pointers and String on LeetCode.