Minimum Number of Swaps to Make the String Balanced - Problem
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 bothAandBare balanced strings, or - It can be written as
[C], whereCis 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.
Input & Output
Example 1 — Basic Unbalanced Case
$
Input:
s = "]]][[["
›
Output:
2
💡 Note:
We have 3 closing brackets followed by 3 opening brackets. Need 2 swaps: swap positions 0,3 and 1,4 to get "[[][]]" which is balanced.
Example 2 — Already Balanced
$
Input:
s = "[]"
›
Output:
0
💡 Note:
String is already balanced with proper opening and closing bracket pairs, so no swaps needed.
Example 3 — Mixed Pattern
$
Input:
s = "]]][[["
›
Output:
1
💡 Note:
Only 1 closing bracket is unmatched at the start. One swap between positions 0 and 3 gives "[]][][" which can be further balanced.
Constraints
- 2 ≤ s.length ≤ 106
- s.length is even
- s consists of exactly s.length/2 opening brackets '[' and s.length/2 closing brackets ']'
Visualization
Tap to expand
Understanding the Visualization
1
Input
Unbalanced string with equal opening and closing brackets
2
Process
Track balance and identify unmatched closing brackets
3
Output
Minimum number of swaps needed
Key Takeaway
🎯 Key Insight: Each swap fixes exactly 2 unmatched brackets, so we need (unmatched + 1) / 2 swaps
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code