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
Minimum Length of String After Deleting Similar Ends INPUT String s = "caabbc" c idx 0 a idx 1 a idx 2 b idx 3 b idx 4 c idx 5 Two Pointer Approach left right Constraints: - Only chars: 'a', 'b', 'c' - Prefix and suffix same char - Cannot overlap ALGORITHM STEPS 1 Initialize Pointers left=0, right=5 s[0]='c' == s[5]='c' OK 2 Remove 'c' from both ends left=1, right=4 String: "aabb" 3 s[1]='a' != s[4]='b' Skip 'a' prefix: left=3 Now s[3]='b' == s[4]='b' 4 Remove 'b' from both ends left=4, right=3 left > right: DONE Process Visualization: "caabbc" (len=6) "aabb" (len=4) "bb" (len=2) "" (len=0) FINAL RESULT Output: 0 Empty String! OK - Optimal Deletions Made: 1. Prefix 'c', Suffix 'c' 2. Prefix 'aa', Suffix 'bb' (Wait - need same char) 2. Prefix 'bb' = Suffix Result: empty Key Insight: Use two pointers from both ends. When chars match, expand inward removing all equal chars. Time: O(n), Space: O(1). The greedy approach works because removing more chars always helps. TutorialsPoint - Minimum Length of String After Deleting Similar Ends | Optimal Two-Pointer Approach
Asked in
Facebook 25 Amazon 20 Google 18
28.0K Views
Medium Frequency
~15 min Avg. Time
891 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