Magicsheet logo

Minimum Length of String After Deleting Similar Ends

Medium
25%
Updated 8/1/2025

Minimum Length of String After Deleting Similar Ends

1. What is this problem about?

This problem involves a simple but iterative process of shrinking a string. You are allowed to perform the following operation as many times as possible:

  1. Pick a non-empty prefix of the string where all characters are the same.
  2. Pick a non-empty suffix of the string where all characters are the same.
  3. The prefix and suffix must have the same character.
  4. The prefix and suffix should not overlap (though they can be adjacent).
  5. Delete both the prefix and the suffix.

Your task is to find the minimum length of the string after performing these operations repeatedly.

2. Why is this asked in interviews?

This is a classic Two Pointers problem often used by Amazon and Goldman Sachs. It evaluates:

  • Pointer Manipulation: Can the candidate move pointers towards each other based on character equality?
  • Edge Case Handling: What happens when the pointers meet? What if the whole string is the same character?
  • Greedy Logic: Understanding that deleting the longest possible prefix/suffix at each step is optimal.

3. Algorithmic pattern used

The Two Pointers pattern is perfect here:

  • Initialize left = 0 and right = length - 1.
  • While left < right and s[left] == s[right]:
    • Store the character at the ends: char = s[left].
    • Move left forward as long as s[left] == char.
    • Move right backward as long as s[right] == char.
  • The final result is max(0, right - left + 1).

4. Example explanation

String: caaaac

  1. left = 0 ('c'), right = 5 ('c'). They match.
  2. Move left: skips index 0. left is now 1.
  3. Move right: skips index 5. right is now 4.
  4. Remaining string is aaaa.
  5. left = 1 ('a'), right = 4 ('a'). They match.
  6. Move left: skips indices 1, 2, 3, 4. left is now 5.
  7. Move right: skips index 4, 3, 2, 1. right is now 0.
  8. left > right, so we stop. Result: 0.

5. Common mistakes candidates make

  • Overlapping Pointers: Not stopping the while loops correctly when the pointers cross, leading to negative lengths or crashes.
  • Handling Single Characters: If the string is "aba", the 'a's match, and we are left with 'b'. If the string is "a", we can't delete anything because we need both a prefix and a suffix.
  • Adjacent Blocks: Not realizing that if the string becomes "aa", both 'a's can be deleted as prefix and suffix even though they are adjacent.

6. Interview preparation tip

Always walk through your Two Pointers logic with a very short string (1-3 characters) to ensure your loop conditions (left < right) and final length calculations are correct.

Similar Questions