#3746
Minimum String Length After Balanced Removals
MediumStringStackCountingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Count the number of 'a's and 'b's. The minimum length is determined by the absolute difference between these counts, as unbalanced characters cannot be removed.
⚙️
Algorithm
3 steps- 1Step 1: Count the occurrences of 'a' and 'b' in the string.
- 2Step 2: Calculate the absolute difference between the counts.
- 3Step 3: Return the difference as the minimum length.
solution.py4 lines
1def min_length_optimal(s):
2 count_a = s.count('a')
3 count_b = s.count('b')
4 return abs(count_a - count_b)ℹ
Complexity note: Single pass through the string gives O(n) complexity with O(1) space.
- 1Removing balanced substrings reduces the string length.
- 2The final length depends only on the unbalanced characters.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.