Minimum Length of String After Deleting Similar Ends Problem
Description
LeetCode Problem 1750.
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
swhere all the characters in the prefix are equal. - Pick a non-empty suffix from the string
swhere all the characters in this suffix are equal. - The prefix and the suffix should not intersect at any index.
- The characters from the prefix and suffix must be the same.
- Delete both the prefix and the suffix.
Return the minimum length of s after performing the above operation any number of times (possibly zero times).
Example 1:
Input: s = "ca"
Output: 2
Explanation: You can't remove any characters, so the string stays as is.
Example 2:
Input: s = "cabaabac"
Output: 0
Explanation: An optimal sequence of operations is:
- Take prefix = "c" and suffix = "c" and remove them, s = "abaaba".
- Take prefix = "a" and suffix = "a" and remove them, s = "baab".
- Take prefix = "b" and suffix = "b" and remove them, s = "aa".
- Take prefix = "a" and suffix = "a" and remove them, s = "".
Example 3:
Input: s = "aabccabba"
Output: 3
Explanation: An optimal sequence of operations is:
- Take prefix = "aa" and suffix = "a" and remove them, s = "bccabb".
- Take prefix = "b" and suffix = "bb" and remove them, s = "cca".
Constraints:
1 <= s.length <= 10^5sonly consists of characters'a','b', and'c'.
Solution
Approach: Two Pointers From Both Ends
Keep a pointer i at the start and j at the end. While s[i] == s[j] and i < j, the two ends share a character, so we can delete the whole run of that character from the front and from the back: move i past every equal character at the front (without passing j), move j back past every equal character at the end (without passing i), then step both once more to remove the last character of each run.
When the ends differ or the pointers meet, nothing more can be removed. The remaining length is max(0, j - i + 1); it can reach 0 when the whole string is one repeated letter.
Complexity: O(n) time, since each pointer moves in one direction, and O(1) extra space.
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)