March LeetCoding Challenge 2021 — Day 8: Remove Palindromic Subsequences

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

Problem Statement

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

Tech-enthusiastic . Connect me — https://twitter.com/sourav__saikia

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store