Minimum String Length After Balanced Removals Problem
Description
LeetCode Problem 3746.
You are given a string s consisting only of the characters 'a' and 'b'.
You are allowed to repeatedly remove any substring where the number of 'a' characters is equal to the number of 'b' characters. After each removal, the remaining parts of the string are concatenated together without gaps.
Return an integer denoting the minimum possible length of the string after performing any number of such operations.
Example 1:
Input: s = "aabbab"
Output: 0
Explanation:
The substring "aabbab" has three 'a' and three 'b'. Since their counts are equal, we can remove the entire string directly. The minimum length is 0.
Example 2:
Input: s = "aaaa"
Output: 4
Explanation:
Every substring of "aaaa" contains only 'a' characters. No substring can be removed as a result, so the minimum length remains 4.
Example 3:
Input: s = "aaabb"
Output: 1
Explanation:
First, remove the substring "ab", leaving "aab". Next, remove the new substring "ab", leaving "a". No further removals are possible, so the minimum length is 1.
Constraints:
1 <= s.length <= 10^5s[i]is either'a'or'b'.
Solution
Approach: Count the letters
Whenever the string contains both letters, some 'a' and 'b' sit next to each other, and removing that pair is a balanced removal. So we can keep removing adjacent ab or ba pairs until only one kind of letter is left.
Each removal takes one of each letter, so what remains is |count_a - count_b| copies of the more frequent letter. No removal can do better, because every balanced substring removes equally many of both letters and the difference of the counts never changes.
Complexity: time O(n), space O(1).
class Solution:
def minLengthAfterRemovals(self, s: str) -> int:
a = s.count("a")
b = len(s) - a
return abs(a - b)