Minimum Length of String After Deleting Similar Ends - Problem
You're given a string s containing only the characters 'a', 'b', and 'c'. Your task is to apply a string reduction operation any number of times to minimize the string's length.

The operation works as follows:
• Choose a non-empty prefix where all characters are identical
• Choose a non-empty suffix where all characters are identical
• The prefix and suffix must not overlap
• The prefix and suffix must contain the same character
• Delete both the prefix and suffix simultaneously

For example, with "cabaac", you could remove prefix "c" and suffix "c" to get "abaa", then remove prefix "a" and suffix "aa" to get "b".

Goal: Return the minimum possible length after performing this operation optimally.

Input & Output

example_1.py — Basic Case
$ Input: s = "ca"
Output: 2
💡 Note: No valid operations can be performed since we need both prefix and suffix with the same character, but 'c' ≠ 'a'.
example_2.py — Multiple Operations
$ Input: s = "cabaac"
Output: 1
💡 Note: First, remove prefix "c" and suffix "c" to get "abaa". Then remove prefix "a" and suffix "aa" to get "b". Final length is 1.
example_3.py — Complete Removal
$ Input: s = "aabccabba"
Output: 3
💡 Note: Remove prefix "aa" and suffix "a" to get "bccabb". Then remove prefix "b" and suffix "bb" to get "cca". No more operations possible, final length is 3.

Constraints

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

Visualization

Tap to expand
String Reduction ProcessOriginal: "cabaac"cabaacLRBoth ends are 'c' - can remove!After removing c's: "abaa"abaaLRBoth ends are 'a' - can remove!After removing a's: "b"bL=ROnly one character left - cannot reduce furtherFinal Answer: Length = 1Time: O(n) | Space: O(1)
Understanding the Visualization
1
Initial Setup
Place pointers at both ends of the string
2
Check Match
If end characters match, we can remove them
3
Maximize Removal
Remove as many matching characters as possible from both ends
4
Continue
Repeat until no more matching pairs exist
5
Final Result
Return the length of remaining characters
Key Takeaway
🎯 Key Insight: Greedy removal of maximum matching characters from both ends always gives the optimal result, since there's no advantage to saving them for later operations.
Asked in
Google 12 Amazon 8 Meta 6 Microsoft 4
28.6K Views
Medium Frequency
~15 min Avg. Time
892 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