Minimum Length of String After Operations - Problem

You are given a string s. You can perform the following process on s any number of times:

Choose an index i in the string such that there is at least one character to the left of index i that is equal to s[i], and at least one character to the right that is also equal to s[i].

Delete the closest occurrence of s[i] located to the left of i.

Delete the closest occurrence of s[i] located to the right of i.

Return the minimum length of the final string s that you can achieve.

Input & Output

Example 1 — Basic Case
$ Input: s = "aabcca"
Output: 5
💡 Note: Character frequencies: a=3, b=1, c=2. Each contributes min(freq, 2): a contributes 2, b contributes 1, c contributes 2. Total: 2+1+2=5
Example 2 — All Different
$ Input: s = "abc"
Output: 3
💡 Note: All characters appear only once, so no operations possible. Final length equals original length: 3
Example 3 — High Frequency
$ Input: s = "aaaa"
Output: 2
💡 Note: Character 'a' appears 4 times, but can only contribute 2 to final result. Operations can reduce 4 a's to 2 a's

Constraints

  • 1 ≤ s.length ≤ 2 × 105
  • s consists of lowercase English letters only

Visualization

Tap to expand
String Length Minimization ProcessOriginal: "aabcca"aabccaRemove triplet patternAfter Operations:aabccFinal Length: 5
Understanding the Visualization
1
Input
String with character frequencies
2
Process
Remove triplet patterns optimally
3
Output
Minimum achievable length
Key Takeaway
🎯 Key Insight: Characters appearing 3+ times can be reduced to at most 2 through optimal removal operations
Asked in
Google 25 Meta 20 Amazon 18
23.4K 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