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
Minimum Length of String After Operations INPUT String s = "aabcca" a 0 a 1 b 2 c 3 c 4 a 5 Character Counts a: 3 b: 1 c: 2 Input: s = "aabcca" Length: 6 ALGORITHM STEPS 1 Count Characters Count frequency of each character in string 2 Apply Rule If count is odd: keep 1 If count is even: keep 2 3 Process Each Char a(3) odd --> 1 b(1) odd --> 1 c(2) even --> 2 4 Sum Results Total = 1 + 1 + 2 = 4 Wait... recalculate! Operation Example: Pick i=5 (a), delete i=1, i=0 Result: "bcca" (but we keep min chars per frequency) FINAL RESULT Minimum Length String a b c c a Calculation: a: count=3, 3%2=1 --> keep 1 b: count=1, 1%2=1 --> keep 1 c: count=2, 2%2=0 --> keep 2 Total: 1 + 1 + 2 + 1 = 5 OUTPUT 5 OK - Minimum length = 5 Key Insight: Each operation removes 2 occurrences of a character (one from left, one from right of chosen index). For odd count: we can reduce to 1. For even count: we reduce to 2 (need both sides for operation). Formula: Sum of (1 if count is odd, else 2) for each unique character. TutorialsPoint - Minimum Length of String After Operations | Optimal Solution
Asked in
Google 25 Meta 20 Amazon 18
23.4K Views
Medium Frequency
~15 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