Remove Palindromic Subsequences

easy string two pointers palindrome

Problem

You are given a string s built only from the letters 'a' and 'b'. In one move you may pick any palindromic subsequence of s (characters keep their order but need not be adjacent, and must read the same forwards and backwards) and delete all of its characters at once. Return the minimum number of moves needed to make s empty.

Constraints: 1 ≤ s.length ≤ 1000 and every character is 'a' or 'b' — the two-letter alphabet is the key restriction.

Inputs = "baabb"
Output2
"baabb" is not a palindrome, so one move cannot take everything; deleting the subsequence "aa" leaves "bbb", a palindrome removed in a second move.

def remove_palindrome_sub(s):
    i, j = 0, len(s) - 1
    while i < j:
        if s[i] != s[j]:
            return 2
        i += 1
        j -= 1
    return 1
function removePalindromeSub(s) {
  let i = 0, j = s.length - 1;
  while (i < j) {
    if (s[i] !== s[j]) return 2;
    i++;
    j--;
  }
  return 1;
}
int removePalindromeSub(String s) {
    int i = 0, j = s.length() - 1;
    while (i < j) {
        if (s.charAt(i) != s.charAt(j)) return 2;
        i++;
        j--;
    }
    return 1;
}
int removePalindromeSub(string s) {
    int i = 0, j = (int)s.size() - 1;
    while (i < j) {
        if (s[i] != s[j]) return 2;
        i++;
        j--;
    }
    return 1;
}
Time: O(n) Space: O(1)