Minimum Length of String After Deleting Similar Ends (LeetCode 1750): Solution and Explanation

Medium
Two Pointers
String

Given a string of the letters a, b and c, repeatedly delete a run of one character from the front together with a run of the same character from the back, and return the shortest length you can reach.

Intuition

An operation is only possible when the first and last characters of what is left are equal. If they differ, no prefix and suffix can share a character, and the string is stuck.

When they are equal, deleting the entire run at each end is never worse than deleting part of it. A partial run would leave the same character at the end, and the next operation would have to remove it anyway.

So the whole process is forced: peel the full run of the shared character from the left, peel it from the right, and repeat. Two pointers l and r mark what is left.

Approach: Two pointers peeling runs

  1. Set l = 0 and r = len(s) - 1.
  2. While l < r and s[l] == s[r]: store ch = s[l].
  3. Move l right while l <= r and s[l] == ch.
  4. Move r left while l <= r and s[r] == ch.
  5. Return r - l + 1. When every character was deleted, l = r + 1 and this is 0.

Step-by-step example

s = "aabccabba"
  1. l = 0, r = 8. Both ends are 'a'.
  2. l moves past "aa" to index 2, and r moves past the final "a" to index 7. What is left is "bccabb".
  3. Both ends are 'b'. l moves past "b" to index 3, and r moves past "bb" to index 5. What is left is "cca".
  4. s[3] = 'c' and s[5] = 'a' differ, so the loop stops. The answer is 5 - 3 + 1 = 3.

Code: Python, Java, C++

1class Solution:
2    def minimumLength(self, s: str) -> int:
3        l, r = 0, len(s) - 1
4        while l < r and s[l] == s[r]:
5            ch = s[l]
6            while l <= r and s[l] == ch:
7                l += 1
8            while l <= r and s[r] == ch:
9                r -= 1
10        return r - l + 1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

l only moves right and r only moves left, and together they cross each index at most once.

Space

O(1)

Only the two pointers and the current character are stored.

Other approaches

Simulate with string slicing (time O(n^2), space O(n))

Strip the matching runs with slicing or strip() calls on a new string each round. The logic is the same, but every round copies what is left, which is quadratic for inputs with many short rounds.

Deque of runs (time O(n), space O(n))

Compress s into runs of (character, count) and pop runs from both ends of a deque while the characters match. It works, but the run list is extra memory for no gain.

Common mistakes

  • Using l < r instead of l <= r inside the inner loops. In "abbba", after the 'a' round the left sweep must eat all three 'b's and let l pass r; with l < r it stops on the last 'b' and returns 1 instead of 0.
  • Stopping the outer loop only on different characters. When a single character is left (l == r), it cannot be deleted because the prefix and suffix would overlap.
  • Deleting one character at a time from each end. In "aaba" the left run of two and the right run of one must go in the same round, or the leftover 'a' blocks the right count.
  • Returning a negative length. After a full delete, r = l - 1 and r - l + 1 is 0, so no clamp is needed if the formula is used as is.

Frequently asked questions

Why is it safe to always delete the whole run?

If only part of a run is deleted, the same character stays at that end. Any future operation must remove it with a matching run on the other side, so taking the whole run now never blocks a deletion that would otherwise be possible.

Can the answer be 0?

Yes. For "cabaabac" every round peels both ends until nothing remains, so l passes r and r - l + 1 is 0.

Why can a single character never be deleted?

The operation needs a non-empty prefix and a non-empty suffix that do not overlap. With one character left, both would have to use the same index.

Does the alphabet size matter?

No. The algorithm only compares characters for equality, so it works for any alphabet. The three-letter limit just keeps the inputs interesting.