Minimum Length of String After Operations

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.

Example 1
Inputs = "abaacbcbb"
Output5
Choosing index 2 removes matching characters at indices 0 and 3, then choosing index 3 removes matching characters at indices 0 and 5, leaving a string of length 5.
Example 2
Inputs = "aa"
Output2
We cannot perform any operations, so we return the length of the original string.

Constraints

  • 1 <= s.length <= 2 * 10^5
  • s consists only of lowercase English letters.

Asked at 3 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate