Minimize String Length - Problem

Given a string s, you have two types of operation:

  1. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the left of i (if exists).
  2. Choose an index i in the string, and let c be the character in position i. Delete the closest occurrence of c to the right of i (if exists).

Your task is to minimize the length of s by performing the above operations zero or more times.

Return an integer denoting the length of the minimized string.

Input & Output

Example 1 — Basic Case
$ Input: s = "ababc"
Output: 3
💡 Note: We can remove one 'a' and one 'b' using the operations, leaving "abc" with length 3. Since all remaining characters are unique, no further reduction is possible.
Example 2 — All Same Characters
$ Input: s = "aaa"
Output: 1
💡 Note: We can remove the duplicates by choosing any 'a' and removing its neighbors. Eventually only one 'a' remains, giving length 1.
Example 3 — Already Unique
$ Input: s = "abc"
Output: 3
💡 Note: All characters are already unique, so no operations are needed. The length remains 3.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Minimize String Length: Remove DuplicatesInput: "ababc"ababcApply deletion operationsduplicateduplicateduplicateResult: Unique characters onlyabcOutput: 3
Understanding the Visualization
1
Input
String with possible duplicate characters
2
Process
Remove duplicates using left/right deletion operations
3
Output
Minimum possible length (count of unique characters)
Key Takeaway
🎯 Key Insight: Only unique characters can remain after all possible deletions
Asked in
Microsoft 15 Amazon 12
23.5K Views
Medium Frequency
~8 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