Remove Palindromic Subsequences Problem
Description
LeetCode Problem 1332.
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.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string if it is generated by deleting some characters of a given string without changing its order. Note that a subsequence does not necessarily need to be contiguous.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: s is already a palindrome, so its entirety can be removed in a single step.
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Constraints:
1 <= s.length <= 1000s[i]is either'a'or'b'.
Solution
Approach: The Answer Is 1 or 2
The key word is subsequence: the characters we remove do not have to be next to each other. A string made of a single repeated letter is always a palindrome, so we can remove all the 'a's in one step (they form "aa...a") and then all the 'b's in a second step. So two steps are always enough.
One step is enough exactly when the whole string is a palindrome, because then we remove it all at once. Otherwise one step cannot empty the string, since that step would have to remove s itself.
So we check whether s reads the same from both ends: if it does, the answer is 1, otherwise 2. The string is never empty, so 0 is not possible.
Complexity: O(n) time and O(1) extra space (the Python version builds the reversed string, O(n)).
class Solution:
def removePalindromeSub(self, s: str) -> int:
# A palindrome goes in one step; otherwise remove all the 'a's, then all the 'b's.
return 1 if s == s[::-1] else 2