March LeetCoding Challenge 2021 — Day 8: Remove Palindromic Subsequences

Sourav Saikia
2 min readMar 8, 2021

--

Today, we will solve the 8th problem of the March LeetCoding Challenge.

Problem Statement

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.

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: String is already palindrome

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".

Example 4:

Input: s = ""
Output: 0

Solution

If we get an empty string, we can return 0 because there is nothing to delete.

If we have a palindrome, we can return 1 because a palindrome can be removed at once.

If not, we can return 2. (At first we can remove ‘a’ or ‘b’ and then we can remove the remaining string)

Time complexity:O(n), n is the length of the string

Space Complexity:O(1), no additional space is used

--

--