Minimum Length of String After Deleting Similar Ends — LeetCode 1750 Python Solution
- Problem
- #1750
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s consisting only of characters 'a', 'b', and 'c'. You are asked to apply the following algorithm on the string any number of times: Pick a non-empty prefix from the string s where all the characters in the prefix are equal.
Example
- Input
- s = "ca"
- Output
- 2
- Explanation
- You can't remove any characters, so the string stays as is.
Python solution
class Solution:
def minimumLength(self, s: str) -> int:
i, j = 0, len(s) - 1
while i < j and s[i] == s[j]:
while i + 1 < j and s[i] == s[i + 1]:
i += 1
while i < j - 1 and s[j - 1] == s[j]:
j -= 1
i, j = i + 1, j - 1
return max(0, j - i + 1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(1) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1750. Minimum Length of String After Deleting Similar Ends is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1750. Minimum Length of String After Deleting Similar Ends?
- LeetCode 1750. Minimum Length of String After Deleting Similar Ends is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1750. Minimum Length of String After Deleting Similar Ends?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1750. Minimum Length of String After Deleting Similar Ends?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1750. Minimum Length of String After Deleting Similar Ends cover?
- LeetCode 1750. Minimum Length of String After Deleting Similar Ends is tagged Two Pointers and String on LeetCode.