Sponsored
Sponsored
If the input string is already a palindrome, then we can remove it in one step. If not, since the string contains only 'a' and 'b', we can always remove all 'a's in one step and all 'b's in another step, making at most two steps. Hence, the minimum number of steps to make the string empty is either 1 (if the string is a palindrome) or 2.
Time Complexity: O(n), where n is the length of string s, as we need to potentially traverse the whole string to check if it's a palindrome.
Space Complexity: O(1), as we use only a few extra variables.
1function removePalindromeSub(s) {
2 const isPalindrome = (s) => {
3 let l = 0, r = s.length - 1;
4 while (l < r) {
5 if (s[l++] !== s[r--]) return false;
6 }
7 return true;
8 };
9 return isPalindrome(s) ? 1 : 2;
10}
The JavaScript function defines a helper to check for the palindrome property. Based on this check, it returns the appropriate minimal steps.
The second approach is based on the observation that the given string only consists of 'a' and 'b'. We can count the unique characters in the string. If the string is non-empty, it will always contain either 'a's or 'b's or both. If it contains both, removing all of one type and then the other would take two steps.
Time Complexity: O(n).
Space Complexity: O(1).
1
Checks for the presence of both 'a' and 'b' in the string and returns the step count accordingly. If only one character type is present, it returns 1; otherwise, it returns 2.