Minimum Number of Swaps to Make the String Balanced - Problem
๐ฏ Minimum Number of Swaps to Make the String Balanced
You are given a string s consisting of exactly n/2 opening brackets '[' and n/2 closing brackets ']', where n is the even length of the string.
A string is considered balanced 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.
Example: "[[]]" is balanced, but "]]][" is not balanced.
You can swap any two brackets at any positions any number of times. Your goal is to find the minimum number of swaps needed to make the string balanced.
Key Insight: Since we have equal numbers of opening and closing brackets, we only need to fix the misplaced closing brackets that appear before their matching opening brackets.
Input & Output
example_1.py โ Basic unbalanced string
$
Input:
s = "][]["
โบ
Output:
1
๐ก Note:
You can make the string balanced by swapping index 0 with index 1 to get "[]", or swap index 0 with index 3 to get "[]]][[" then swap index 1 with index 2 to get "[[]]".
example_2.py โ Already balanced
$
Input:
s = "[]"
โบ
Output:
0
๐ก Note:
The string is already balanced, so no swaps are needed.
example_3.py โ Complex case
$
Input:
s = "]]]][[[["
โบ
Output:
2
๐ก Note:
We have 4 unmatched closing brackets at the beginning. We can fix 2 unmatched closing brackets with 1 swap, so we need 2 swaps total: ceil(4/2) = 2.
Constraints
- n == s.length
- 2 โค n โค 106
- n is even
- s[i] is either '[' or ']'
- The number of opening brackets '[' equals the number of closing brackets ']'
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Balance
Start with balance = 0, like an empty bank account
2
Process Brackets
Opening brackets add 1, closing brackets subtract 1 from balance
3
Track Debt
When balance goes negative, count the 'debt' and reset balance to 0
4
Calculate Swaps
Each swap fixes 2 units of debt, so swaps = ceil(debt / 2)
Key Takeaway
๐ฏ Key Insight: Track the running balance of brackets - when it goes negative, we have unmatched closing brackets that need swapping. Each swap fixes exactly 2 unmatched brackets.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code