Minimum Length of String After Deleting Similar Ends — LeetCode 1750 Python Solution

MediumTwo PointersString
Problem
#1750
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview