Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1332. Remove Palindromic Subsequences - Leetcode Solution

Code Implementation

class Solution:
    def removePalindromeSub(self, s: str) -> int:
        # If the string is empty, no need to remove anything
        if not s:
            return 0
        # If the string is a palindrome, remove it in one operation
        if s == s[::-1]:
            return 1
        # Otherwise, remove all 'a's in one operation and all 'b's in another
        return 2
      
class Solution {
public:
    int removePalindromeSub(string s) {
        if (s.empty()) return 0;
        string t = s;
        reverse(t.begin(), t.end());
        if (s == t) return 1;
        return 2;
    }
};
      
class Solution {
    public int removePalindromeSub(String s) {
        if (s.isEmpty()) return 0;
        StringBuilder sb = new StringBuilder(s);
        if (s.equals(sb.reverse().toString())) return 1;
        return 2;
    }
}
      
var removePalindromeSub = function(s) {
    if (!s) return 0;
    let reversed = s.split('').reverse().join('');
    if (s === reversed) return 1;
    return 2;
};
      

Problem Description

You are given a string s consisting only of the characters 'a' and 'b'. In one operation, you can remove any palindromic subsequence from s. Your task is to return the minimum number of operations needed to make s empty.

  • A subsequence is a sequence derived from s by deleting some (possibly zero) characters without changing the order of the remaining characters.
  • A palindrome is a string that reads the same backward as forward.
  • You can remove any palindromic subsequence as a single operation.
  • Key constraints: The string contains only 'a' and 'b'. You may not reuse elements for a single operation, but may remove any palindromic subsequence in each operation.

Thought Process

The first step is to understand what it means to remove a palindromic subsequence. Since a subsequence can skip characters, you can pick any subset of indices, as long as the resulting string is a palindrome.

At first glance, the problem might look similar to the classic "remove palindromic substrings" problem, but here, subsequences make it more flexible. The brute-force approach would be to try removing all possible palindromic subsequences, but that's computationally expensive.

However, since the string only contains 'a' and 'b', we can think about how to minimize the number of operations. If the whole string is already a palindrome, we can remove it in one operation. If not, can we do it in two? For example, by removing all 'a''s in one operation (since "aaa...a" is a palindrome) and all 'b''s in another.

This leads to a key insight: we never need more than two operations for any string made of only 'a' and 'b'.

Solution Approach

  • Step 1: Check if the string s is empty. If so, return 0 because no operations are needed.
  • Step 2: Check if s is a palindrome. This can be done by comparing s to its reverse.
  • Step 3: If s is a palindrome, you can remove the entire string in one operation, so return 1.
  • Step 4: If s is not a palindrome, you can always remove all 'a's in one operation (since that subsequence is a palindrome) and all 'b's in another operation. Thus, return 2.

Why does this work? Because any string of 'a' and 'b' can be reduced by removing all of one character at a time, and both "aaa...a" and "bbb...b" are palindromes.

This approach is efficient and leverages the constraint that the string contains only two types of characters.

Example Walkthrough

Let's walk through an example with s = "ababa":

  • First, check if "ababa" is a palindrome. Since it reads the same forwards and backwards, it is a palindrome.
  • Therefore, we can remove the entire string in one operation. The answer is 1.

Another example: s = "abb"

  • "abb" is not a palindrome ("abb" != "bba").
  • First operation: Remove all 'a's ("a" is a palindrome subsequence), leaving "bb".
  • Second operation: Remove all 'b's ("bb" is a palindrome subsequence), leaving an empty string.
  • Total operations: 2.

Time and Space Complexity

  • Brute-force approach: Would involve generating all possible palindromic subsequences, which is exponential in time and space.
  • Optimized approach (used here):
    • Checking if the string is a palindrome takes O(n) time, where n is the length of the string.
    • Space complexity is O(1) (or O(n) if you count the reverse string, but that's negligible for most practical purposes).
    • Overall, the solution runs in O(n) time and O(1) to O(n) space.

Summary

The key insight in this problem is recognizing that, with only two types of characters, any string can be made empty in at most two operations: removing all of one character at a time. If the string is already a palindrome, it can be removed in one operation. This leads to a simple, efficient solution with linear time complexity.

The elegance of the solution comes from leveraging the constraints and properties of palindromic subsequences, and recognizing that brute-force is unnecessary.