Minimum Length of String After Deleting Similar Ends - 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.
  • Pick a non-empty suffix from the string s where 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 suffix.

Return the minimum length of s after performing the above operation any number of times (possibly zero times).

Input & Output

Example 1 — Basic Removal
$ Input: s = "caabbc"
Output: 0
💡 Note: Remove prefix "c" and suffix "c" → "aabb". Then remove prefix "aa" and suffix "bb" → "". Final length is 0.
Example 2 — Partial Removal
$ Input: s = "aabccabba"
Output: 3
💡 Note: Remove prefix "aa" and suffix "a" → "bccabb". Remove prefix "b" and suffix "bb" → "cca". No more removals possible. Final length is 3.
Example 3 — No Removal
$ Input: s = "abc"
Output: 3
💡 Note: No matching prefix-suffix pairs exist (a ≠ c, b can't form both prefix and suffix without overlap). Final length is 3.

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists only of characters 'a', 'b', and 'c'

Visualization

Tap to expand
String Layer Removal ProcessInput:caabbcStep 1:aabbRemove c+cStep 2:Empty StringRemove aa+bbFinal Length: 0
Understanding the Visualization
1
Input
String with characters a, b, c
2
Process
Remove matching prefix-suffix pairs layer by layer
3
Output
Minimum remaining length after all possible removals
Key Takeaway
🎯 Key Insight: Use two pointers to greedily remove the longest matching character layers from both ends
Asked in
Facebook 25 Amazon 20 Google 18
28.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen