Skip to main content
Back to problems
#3746
Medium Algorithms

Minimum string length after balanced removals

String Stack Counting
78.4% acceptance
Feb 25, 2026
59
6
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_length_after_removals(s: String) -> i32 {
    let ca = s.bytes().filter(|&b| b == b'a').count() as i32;
    let cb = s.len() as i32 - ca;
    (ca - cb).abs()
  }
}