Minimum Length of String After Deleting Similar Ends

Remove runs of the same letter from both ends of a string, again and again, and find how short it can get.

You are given a string s made of the letters a, b and c. In one move, you pick a letter, remove one or more copies of it from the start of the string and one or more copies of it from the end. Every removed character must be that letter, and the same character cannot be removed from both sides at once. You may make as many moves as you like. Return the smallest length the string can reach.

Example 1
Input: s = "ca"
Output: 2
Explanation: the string starts with c and ends with a, so no move is possible.
Example 2
Input: s = "cabaabac"
Output: 0
Explanation: remove c from both ends, then a, then b, and then the two a's left in the middle.
Example 3
Input: s = "aabccabba"
Output: 3
Explanation: remove "aa" from the start and "a" from the end, then "b" and "bb", leaving "cca".
Solution

The Idea

Think of the string as a row of letter tiles. You may take tiles off both ends at the same time, as long as every tile you take shows the same letter. A move is only possible when the first tile and the last tile match, so only the two ends of the row ever matter.

Take Example 3, "aabccabba". It starts with a and ends with a, so a move is possible. The start has two a's in a row and the end has one. How many should we take? All of them, from both ends, because taking fewer never helps. A leftover a at the start can only go in a later move of a's, so it might as well go now. And once the end no longer shows an a, a leftover a at the start would block every later move.

So each move takes the whole run of the letter from both ends, where a run is a stretch of the same letter in a row. Look at the picture below, which follows Example 3 from the top row down. The marker left points at the first tile still there, and right at the last one.

The string aabccabba in three rows. First left is on index 0 and right on index 8, both a, so the a's at both ends go. Then left is on 2 and right on 7, both b, so the b's go. Then left is on c and right on a, which differ, so the search stops with cca, length 3.

In the top row, left and right both show a, so the a's at indexes 0, 1 and 8 go. In the middle row the removed tiles are greyed out, and the ends are now b at index 2 and b at index 7. That move removes the b's at indexes 2, 6 and 7. In the bottom row the ends are c and a, which differ, so no move is left. Three tiles remain, "cca", and the answer is 3.

Notice that nothing was actually deleted. The two markers simply walked toward each other, and the tiles between them are what is left of the string. Moving two markers through the data like this is called the two-pointer technique; Two Pointers Basics shows more problems that use it.

Solution Approach

Turning that idea into code means settling three things: how to keep track of what is left of the string, how far each marker moves in one move, and when to stop.

Tracking what is left

Why not cut the ends off the string itself, with substring? Each cut builds a new string and copies every character that is left. Take a string of n letters where most moves remove one letter from each end, such as "abcabccbacba". It needs about n/2 copies of up to n characters each, so about n² steps. Two indexes, left and right, describe the same part of the string without copying anything.

How far each marker moves

Where does a move end? left moves right while it points at the letter of the move, and right moves left in the same way. Both check that left is still at or before right, so they never run off the part that is left.

That check allows left and right to be on the same index. In "aaa", left takes all three a's and ends up past right. Removing "aa" from the start and "a" from the end is a real move, because the two parts do not share a character, so the string can become empty.

When to stop

When is no move left? Either the letters at left and right differ, or fewer than two letters are left. In "aba" the a's go and the b stays: it is both the first and the last letter, but removing it from both ends would remove the same character twice. So the moves go on only while left is before right.

The length that is left is right - left + 1. When the markers have crossed, left is one past right and the formula gives 0.

Java Solution

The method minimumLength works in these steps:

  1. First, put left on index 0 and right on the last index, s.length() - 1.
  2. An outer loop makes one move per round. It runs while left is before right and the letters at both markers are equal. Inside, save the letter at left in c.
  3. A first inner loop moves left right past every c at the start, as long as left <= right.
  4. A second inner loop moves right left past every c at the end, with the same check.
  5. When the outer loop stops, return right - left + 1.

The main method runs the three examples, then "aaa", where every letter can go, "aba", where one letter stays in the middle, and the single letter "a".

Java
public class MinimumLengthOfString {

    public static int minimumLength(String s) {
        int left = 0;
        int right = s.length() - 1;
        while (left < right && s.charAt(left) == s.charAt(right)) {
            char c = s.charAt(left);
            while (left <= right && s.charAt(left) == c) {
                left++;                       // remove the whole run of c at the start
            }
            while (left <= right && s.charAt(right) == c) {
                right--;                      // and the whole run of c at the end
            }
        }
        return right - left + 1;              // 0 when the markers have crossed
    }

    public static void main(String[] args) {
        String[] tests = {"ca", "cabaabac", "aabccabba", "aaa", "aba", "a"};
        for (String s : tests) {
            System.out.println("\"" + s + "\" -> " + minimumLength(s));
        }
    }
}

Running it prints:

Output
"ca" -> 2
"cabaabac" -> 0
"aabccabba" -> 3
"aaa" -> 0
"aba" -> 1
"a" -> 1

Look at "cabaabac" -> 0. Its last move has left on index 3 and right on index 4, two a's side by side. The first inner loop takes both, so left ends on 5, past right, and the result is 4 - 5 + 1 = 0. "aaa" -> 0 shows the same thing in one move.

Both lines depend on the <= in the inner loops. With left < right there instead, the first inner loop stops one letter early, on the last a. The second inner loop then cannot move either, so that a is never removed: the same two inputs return 1 instead of 0.

The last two lines come from the outer loop's check. "aba" -> 1 loses its a's and keeps the b, since one letter cannot be removed from both ends at once. "a" -> 1 never enters the loop at all, because left and right start on the same index.

Complexity

The markers only ever move toward each other, so the work is a single pass over the string.

  • Time: O(n), where n is the length of the string. left only moves right and right only moves left, so together they take at most n steps before they cross.
  • Space: O(1). No new string is built; the method keeps two indexes and the current letter.

Valid Palindrome also compares the two ends of a string while moving inward.