Remove Palindromic Subsequences - 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.

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 it reads the same backward as well as forward.

Input & Output

Example 1 — Not a Palindrome
$ Input: s = "abab"
Output: 2
💡 Note: String "abab" is not a palindrome. We can remove all 'a's in step 1 ("aa" is palindrome) and all 'b's in step 2 ("bb" is palindrome).
Example 2 — Already Palindrome
$ Input: s = "aba"
Output: 1
💡 Note: String "aba" is already a palindrome, so we can remove the entire string in 1 step.
Example 3 — Empty String
$ Input: s = ""
Output: 0
💡 Note: Empty string requires 0 steps as there are no characters to remove.

Constraints

  • 0 ≤ s.length ≤ 1000
  • s consists only of letters 'a' and 'b'

Visualization

Tap to expand
Remove Palindromic Subsequences INPUT String s (only 'a' and 'b') a b a b 0 1 2 3 Input Value: s = "abab" Constraints: - Only 'a' and 'b' chars - Remove palindromic subsequences "abab" != "baba" (Not palindrome) ALGORITHM STEPS 1 Check Empty If s is empty: return 0 2 Check Palindrome If s == reverse(s): return 1 3 Otherwise Return 2 (always!) 4 Why 2 Steps Max? All 'a's form palindrome All 'b's form palindrome For "abab": Step 1: Remove "aa" a b a Step 2: Remove "bb" b b FINAL RESULT Minimum Steps Required 2 Output: 2 Verification: 1. s="" empty? No 2. "abab"=="baba"? No 3. Answer = 2 [OK] Key Insight: Since string only contains 'a' and 'b', any subsequence of same characters is automatically a palindrome! Max 2 steps: first remove all 'a's (palindrome "aaa..."), then remove all 'b's (palindrome "bbb..."). This is an O(n) solution - just check if empty (0), palindrome (1), or else (2). TutorialsPoint - Remove Palindromic Subsequences | Optimal Solution O(n)
Asked in
Facebook 15 Google 8
28.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen