Python 1332.py
class Solution:
def removePalindromeSub(self, s: str) -> int:
# empty
if not s:
return 0
# palindrome
if s == s[::-1]:
return 1
# 1. generate a subsequence consisting of a's only => that's a palindrome, remove it
# 2. only b's are left => that's a palindrome, too, can be removed
return 2
Difficulty
and has an acceptance rate of about 77% (200k+ submissions).
Typical patterns to solve this problem:
- String
- Two Pointers
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of determining the minimum number of operations required to delete a string composed only of the characters 'a' and 'b'. Each operation removes a palindromic subsequence. The algorithm leverages the fact that any string of this form can be cleared in at most two steps: one step to delete all 'a' characters (which form a palindrome) and a second step to delete the remaining 'b' characters. The code follows a straightforward decision tree that quickly resolves the answer for all possible inputs.
Key Steps
Handling an Empty Input
The first conditional checks whether the input string is empty. An empty string requires no deletions, so the function returns 0.
if not s:
return 0
Detecting a Whole-String Palindrome
If the string is not empty, the next step determines whether the entire string is already a palindrome. This is done by comparing the string to its reverse, which is obtained using Python’s slice notation s[::-1]. When the string reads the same forward and backward, a single deletion of the whole string suffices, and the function returns 1.
if s == s[::-1]:
return 1
Default Case - Two Deletions
When the string is neither empty nor a palindrome, the algorithm concludes that exactly two deletions are necessary. The first deletion removes all 'a' characters (forming a palindrome), and the second deletion removes the remaining 'b' characters (also a palindrome). The function therefore returns 2.
return 2
Edge Cases Addressed
The code explicitly handles the situation where the input string has length zero, ensuring that no further processing occurs and that the correct result of 0 is produced.
It also correctly identifies strings that are already palindromic, regardless of length, including single-character strings such as "a" or "b". In these cases the early return of 1 avoids unnecessary computation.
For any non-palindromic combination of 'a' and 'b', the algorithm reliably falls back to the constant answer 2, covering all remaining possibilities without additional branching.
Performance Optimizations
The implementation achieves optimal performance by employing early exits. The empty-string check prevents any further work when there is nothing to process. The palindrome test uses Python’s built-in slicing, which creates the reversed string in linear time and then performs a direct equality comparison; this avoids explicit loops and leverages highly optimized C-level operations inside the interpreter.
By structuring the logic as a sequence of immediate returns, the function eliminates the need for auxiliary data structures or iterative processing, resulting in minimal memory usage and constant-time decision making after the palindrome check. This design ensures that the solution runs as fast as possible for all input sizes within the problem constraints.
ELI5 - Simplified Explanation
Imagine a line of colorful building blocks standing in a row. Some are red and some are blue. Our goal is to clear all the blocks away, but there is a special rule. We can only remove a group of blocks if they form a perfect mirror image, meaning they look the same whether you look at them from the left side or the right side.
The computer looks at the row of blocks first. If there are no blocks at all, the job is already done. When the blocks are already in a perfect mirror pattern, the computer grabs the whole line and clears it in just one move.
If the blocks are mixed up, the computer uses a clever trick. It first picks out all the red blocks. Because they are the same color, they act like a mirror image, so they can be taken away together. After those are gone, only the blue blocks are sitting there. Since all the remaining blocks are now the same color, they also form a mirror image and can be taken away in one final turn. This way, any line made of only two colors can always be cleared in two groups.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| lzl124631x | C++ | |||||||||||
| martianoff | Scala | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1331: Rank Transform of an Array
- problem 1475: Final Prices With a Special Discount in a Shop
- problem 424: Longest Repeating Character Replacement
- problem 1558: Minimum Numbers of Function Calls to Make Target Array
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality