Minimize String Length - Problem
Minimize String Length
You are given a string
Operation 1: Choose any character at position
Operation 2: Choose any character at position
Your goal is to perform these operations as many times as needed to achieve the minimum possible string length.
Example: In string
Return the length of the minimized string after performing optimal operations.
You are given a string
s and need to minimize its length using two powerful operations:Operation 1: Choose any character at position
i, then delete the closest duplicate of that character to the left of position i (if it exists).Operation 2: Choose any character at position
i, then delete the closest duplicate of that character to the right of position i (if it exists).Your goal is to perform these operations as many times as needed to achieve the minimum possible string length.
Example: In string
"abbaca", you can eliminate duplicate 'a's and 'b's, leaving only unique characters.Return the length of the minimized string after performing optimal operations.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "aaabc"
โบ
Output:
3
๐ก Note:
We can eliminate duplicate 'a's by choosing any 'a' and removing its closest duplicate. After optimal operations, we're left with one 'a', one 'b', and one 'c', giving us length 3.
example_2.py โ Mixed Duplicates
$
Input:
s = "abbaca"
โบ
Output:
3
๐ก Note:
Starting with 'abbaca', we can remove duplicate 'a's and 'b's through strategic operations. The final result contains one copy each of 'a', 'b', and 'c', so the minimum length is 3.
example_3.py โ All Same Characters
$
Input:
s = "aaaa"
โบ
Output:
1
๐ก Note:
When all characters are the same, we can eliminate all but one through repeated operations, leaving a string of length 1.
Constraints
- 1 โค s.length โค 1000
- s consists of lowercase English letters only
- The string is guaranteed to be non-empty
Visualization
Tap to expand
Understanding the Visualization
1
Initial Analysis
Identify all the characters and their frequencies in the string
2
Elimination Strategy
Realize that any duplicate character can be eliminated through left/right operations
3
Optimal Insight
The minimum length equals the number of unique characters
4
Count Unique
Use a hash set to count distinct characters in one pass
Key Takeaway
๐ฏ Key Insight: No matter the order of operations, we can always eliminate all duplicate characters through strategic left/right deletions, leaving exactly one copy of each unique character.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code