Minimum Length of String After Operations - Problem
Minimum Length of String After Operations
You are given a string
1. Choose an index
2. Delete the closest occurrence of
3. Delete the closest occurrence of
4. Delete the character at index
This removes exactly 3 characters in one operation. Your goal is to find the minimum possible length of the final string after performing these operations optimally.
Example: In string
You are given a string
s and can perform a special triple-deletion operation any number of times. In each operation, you:1. Choose an index
i where character s[i] appears at least once to the left AND at least once to the right2. Delete the closest occurrence of
s[i] to the left of index i3. Delete the closest occurrence of
s[i] to the right of index i4. Delete the character at index
i itselfThis removes exactly 3 characters in one operation. Your goal is to find the minimum possible length of the final string after performing these operations optimally.
Example: In string
"ababa", if we choose index 2 (middle 'a'), we can delete the 'a' at index 0 (closest left), the 'a' at index 4 (closest right), and the 'a' at index 2, leaving us with "bb". Input & Output
example_1.py โ Basic Case
$
Input:
s = "aabcc"
โบ
Output:
4
๐ก Note:
We have 'a':2, 'b':1, 'c':2. No character appears โฅ3 times, so no operations possible. Length remains 5. Wait, that's wrong. Let me recalculate: We cannot perform any operations because no character has occurrences on both left and right of another same character. Final length is 5.
example_2.py โ Single Operation
$
Input:
s = "ababa"
โบ
Output:
2
๐ก Note:
Character 'a' appears 3 times. We can choose middle 'a' (index 2), delete closest left 'a' (index 0), closest right 'a' (index 4), and the middle 'a' itself. This removes 3 characters, leaving "bb" with length 2.
example_3.py โ Multiple Characters
$
Input:
s = "aabbbcccc"
โบ
Output:
6
๐ก Note:
Frequencies: 'a':2, 'b':3, 'c':4. Using the formula: 'a' contributes 2%3=2, 'b' contributes 3 (since 3%3=0 and count>0), 'c' contributes 4%3=1. Total: 2+3+1=6.
Constraints
- 1 โค s.length โค 105
- s consists of lowercase English letters only
- Each operation removes exactly 3 characters
Visualization
Tap to expand
Understanding the Visualization
1
Recognize the Pattern
Each operation removes exactly 3 characters of the same type
2
Order Independence
The final result doesn't depend on the order of operations
3
Apply Formula
For n occurrences: remaining = n % 3 (minimum 3 if divisible by 3)
Key Takeaway
๐ฏ Key Insight: Transform a complex O(nยณ) simulation into an O(n) mathematical formula by recognizing that operation order doesn't affect the final result - only character frequencies matter!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code