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:
4
💡 Note:
We can choose index 1 (second 'a'), which has 'a' at position 0 (left) and 'a' at positions 4,5 (closest right is 4). Remove positions 0 and 4, leaving 'abcc' with length 4.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code