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 INPUT String s = "ababc" a b a b c 0 1 2 3 4 Duplicate Characters: 'a' x 2 'b' x 2 Unique Characters: 'c' x 1 Length = 5 Unique chars: a, b, c ALGORITHM STEPS 1 Use Set/Hash Track unique characters 2 Iterate String Add each char to set 3 Duplicates Removed Set keeps only unique 4 Return Set Size Count = min length Set Contents: a b c set.size() = 3 FINAL RESULT Minimized String: a b c Output: 3 OK - Verified! Min length achieved Original: 5 chars Minimized: 3 chars Removed 2 duplicates Key Insight: The minimum possible length equals the number of UNIQUE characters in the string. Using the delete operations, we can always remove all duplicate occurrences of any character, leaving exactly one of each unique character. Solution: return len(set(s)) - O(n) time, O(k) space. TutorialsPoint - Minimize String Length | Optimal Solution
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