Minimum Length of String after Deleting Similar Ends

Medium Topics Company Tags

You may remove a nonempty prefix and a nonempty suffix from s in one operation if both consist entirely of the same character. The two pieces must not overlap. Repeat this operation as often as you wish and return the smallest remaining length. A single character cannot be used as both pieces.

Example 1:

Input: s = "a"

Output: 1

Explanation: There is only one character, so a nonempty prefix and suffix cannot be chosen without overlapping.

Example 2:

Input: s = "aa"

Output: 0

Explanation: Choose the first "a" as the prefix and the second "a" as the suffix. Removing both leaves an empty string.

Example 3:

Input: s = "ab"

Output: 2

Explanation: The first and last characters differ, so no operation can be performed. Both characters remain.

Constraints:

  • 1 <= s.length <= 100000
  • Each character is a, b, or c.


Topics

Company Tags

Please upgrade to NeetCode Pro to view company tags.