Minimum Length of String After Operations

Medium Topics Company Tags

Choose a character with another occurrence of the same letter on each side. Remove the closest matching letter on its left and the closest matching letter on its right, keeping the chosen character. Repeat as often as desired. Return the shortest string length you can reach.

Example 1:

Input: s = "ababa"

Output: 3

Explanation: Choose the middle "a" and remove the nearest "a" on each side, leaving "bab". No remaining character has a matching character on both sides, so the final length is 3.

Example 2:

Input: s = "aaaa"

Output: 2

Explanation: One operation removes two of the four "a" characters, leaving "aa". Two characters are not enough to perform another operation.

Example 3:

Input: s = "abc"

Output: 3

Explanation: Every letter occurs only once, so no character has matching letters on both sides. The string stays length 3.

Constraints:

  • 1 <= s.length <= 200000
  • Only lowercase English letters occur.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.