algoadvance

Leetcode 1332. Remove Palindromic Subsequences

Problem Statement

  1. Remove Palindromic Subsequences

Given a string s consisting only of letters ‘a’ and ‘b’, you can delete any palindromic subsequence from s. Return the minimum number of steps to make the given string empty.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

A string is called palindromic if it reads the same backward as forward.

Clarifying Questions

  1. What characters are allowed in the string: The string consists only of letters ‘a’ and ‘b’.
  2. What is the length range of the string s: The length of the string can range from 1 to 1000.
  3. What should be returned: We should return the minimum number of steps required to make the given string empty.

Strategy

Key Points to Consider:

  1. Checking if the String is Palindromic:
    • If the string is already a palindrome, we can remove it entirely in one step.
  2. Handling Non-Palindromic Strings:
    • If the string is not a palindrome, we can delete all ‘a’s in one step and all ‘b’s in another step or vice versa. This will always take exactly 2 steps.

Steps:

  1. Check if the input string s is a palindrome.
  2. If it is a palindrome, return 1.
  3. If it is not a palindrome, return 2.

Code

public class Solution {
    public int removePalindromeSub(String s) {
        if (s == null || s.isEmpty()) {
            return 0;
        }
        if (isPalindrome(s)) {
            return 1;
        }
        return 2;
    }
    
    private boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right) {
            if (s.charAt(left) != s.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        // Example usage:
        System.out.println(solution.removePalindromeSub("ababa")); // Output: 1
        System.out.println(solution.removePalindromeSub("abb"));   // Output: 2
        System.out.println(solution.removePalindromeSub("baabb")); // Output: 2
    }
}

Time Complexity

Space Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI