Minimum Length of String After Operations Problem
#3223
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3223.
You are given a string s.
You can perform the following process on s any number of times:
- Choose an index
iin the string such that there is at least one character to the left of indexithat is equal tos[i], and at least one character to the right that is also equal tos[i]. - Delete the closest occurrence of
s[i]located to the left ofi. - Delete the closest occurrence of
s[i]located to the right ofi.
Return the minimum length of the final string s that you can achieve.
Example 1:
Input: s = "abaacbcbb"
Output: 5
Explanation:
We do the following operations:
- Choose index 2, then remove the characters at indices 0 and 3. The resulting string is s = "bacbcbb".
- Choose index 3, then remove the characters at indices 0 and 5. The resulting string is s = "acbcb".
Example 2:
Input: s = "aa"
Output: 2
Explanation:
We cannot perform any operations, so we return the length of the original string.
Constraints:
1 <= s.length <= 2 * 10^5sconsists only of lowercase English letters.
Solution
Approach: Counting
Each operation removes two copies of a character, so for a character that appears x times, an odd count leaves one copy and an even count leaves two copies (counts below 3 stay unchanged, which gives the same formula). Count each character and add 1 for every odd count and 2 for every even (non-zero) count.
Complexity: time O(n), space O(|Σ|), where |Σ| = 26.
class Solution:
def minimumLength(self, s: str) -> int:
cnt = Counter(s)
return sum(1 if x & 1 else 2 for x in cnt.values())