#1963
Medium Algorithms Minimum number of swaps to make the string balanced
Two Pointers String Stack Greedy
78.1% acceptance
Feb 25, 2026
2562
150
You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.
A string is called balanced if and only if:
It is the empty string, or
It can be written as AB, where both A and B are balanced strings, or
It can be written as [C], where C is a balanced string.
You may swap the brackets at any two indices any number of times.
Return the minimum number of swaps to make s balanced.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_swaps(s: String) -> i32 {
let mut unmatched = 0;
for ch in s.chars() {
if ch == '[' {
unmatched += 1;
} else {
if unmatched > 0 {
unmatched -= 1;
}
}
}
// unmatched is the number of unmatched '[' which equals unmatched ']'
// each swap fixes 2 unmatched pairs
(unmatched + 1) / 2
}
}