Python 1750.py
class Solution:
def minimumLength(self, s: str) -> int:
left = 0
right = len(s) - 1
while left < right and s[left] == s[right]:
what = s[left]
# prefix
while left <= right and s[left] == what:
left += 1
# suffix
while left <= right and s[right] == what:
right -= 1
return right - left + 1
Difficulty
and has an acceptance rate of about 56% (300k+ 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 computes the length of the shortest possible string that remains after repeatedly removing matching characters from both the beginning and the end of the input. It uses a two-pointer technique that advances from the left and right ends toward the center while the characters at the two pointers are equal. When a matching character is found, the algorithm skips over the entire contiguous block of that character on both sides before continuing the comparison. The final result is the distance between the two pointers plus one, which corresponds to the length of the unreduced middle segment.
Key Steps
Initialisation of Pointers
The algorithm starts by placing one pointer at the first character and another at the last character of the string.
left = 0
right = len(s) - 1
These pointers define the current window that is still under consideration.
Main Loop - Matching Ends
The core of the method is a loop that continues as long as the left pointer is strictly to the left of the right pointer and the characters at both ends are identical.
while left < right and s[left] == s[right]:
When this condition holds, the character that appears at both ends is stored for subsequent skipping.
what = s[left]
Skipping the Prefix Block
Once a matching character is identified, the algorithm moves the left pointer forward while the character at the left pointer remains equal to the stored value. This effectively discards the whole contiguous block of that character at the beginning of the current window.
while left <= right and s[left] == what:
left += 1
Skipping the Suffix Block
Symmetrically, the right pointer is moved backward while the character at the right pointer equals the stored value, removing the contiguous block at the end of the current window.
while left <= right and s[right] == what:
right -= 1
Termination and Result Computation
When the outer loop exits-either because the pointers have crossed or the characters at the ends differ-the length of the remaining substring is calculated as the distance between the pointers plus one.
return right - left + 1
If the pointers have crossed, the expression yields a non-positive value, and the addition of one correctly returns zero, indicating that the entire string has been eliminated.
Edge Cases Handled
The algorithm gracefully deals with several special inputs without requiring explicit checks.
When the input string is empty, len(s) - 1 evaluates to -1. The condition left < right fails immediately, and the final expression right - left + 1 becomes 0, correctly reporting an empty result.
For a single-character string, left and right both start at 0. The outer loop condition left < right is false, so the loop body is skipped and the return expression yields 1, reflecting that no removal is possible.
If the entire string consists of the same character repeated, the inner prefix and suffix loops will advance left past right. The final calculation then returns 0, indicating that the whole string can be removed.
When the string begins and ends with the same character but contains a different interior segment (for example, "aaXYZaa"), the algorithm removes the outer blocks of 'a' and stops as soon as the characters at the new ends differ, leaving the interior "XYZ" untouched. The returned length corresponds precisely to the length of that interior segment.
Performance Optimisations
The solution achieves efficiency by avoiding element-wise removal or string reconstruction. Instead, it works directly with index variables, which means each character is examined at most a constant number of times. The inner loops skip entire runs of identical characters in a single pass, preventing repeated comparisons for each character in those runs. By moving both pointers inward simultaneously whenever a matching outer character is found, the algorithm reduces the search space as quickly as possible, leading to a linear traversal of the input string. This in-place pointer manipulation eliminates the overhead of auxiliary data structures and keeps the runtime proportional to the length of the original string.
ELI5 - Simplified Explanation
Imagine a long train made of colored blocks. The blocks are sitting in a row, and each one has a specific color.
This code acts like a playful friend helping to match blocks from both ends of the train. It starts by looking at the very first block on the left side and the very last block on the right side.
If those two blocks are the exact same color, the code decides to take them away. It keeps looking at the next blocks too. If the left side has a bunch of red blocks in a row, it removes all of them. If the right side also has a bunch of red blocks, it removes those as well.
It keeps doing this dance where it checks the ends, sees if the colors match, and clears away the matching colors from both sides. It continues this process over and over as long as the ends match and there are still blocks left in the middle.
Once the blocks at the ends are different colors, the code stops. It just looks at the remaining blocks that are still sitting there in the middle of the train and counts how many are left.
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 | C | Go | Rust | TS | |||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C, C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| pruthvikp | Python | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1462: Course Schedule IV
- problem 1497: Check If Array Pairs Are Divisible by k
- problem 1574: Shortest Subarray to be Removed to Make Array Sorted
- problem 1590: Make Sum Divisible by P
- problem 1654: Minimum Jumps to Reach Home
- problem 1733: Minimum Number of People to Teach
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