Minimum Number of Swaps to Make the String Balanced
You are given a string `s` of even length `n` that contains exactly `n / 2` opening brackets `[` and `n / 2` closing brackets `]`. A string is balanced if it is empty, or is `AB` with both `A` and `B` balanced, or is `[C]` with `C` balanced. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps needed to make `s` balanced.
30:00
Minimum Number of Swaps to Make the String Balanced
You are given a string s of even length n that contains exactly n / 2 opening brackets [ and n / 2 closing brackets ]. A string is balanced if it is empty, or is AB with both A and B balanced, or is [C] with C balanced. You may swap the brackets at any two indices any number of times. Return the minimum number of swaps needed to make s balanced.
Example 1:
Input: {"s":"][]["}
Output: 1
Constraints:
n=s.length
2≤n≤106
n is even.
s[i] is either '[' or ']'.
The number of '[' equals n / 2, and the number of ']' equals n / 2.
Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result
Run code to see results.
Input
arr ={"s":"][]["}
s, scanned left to right: matched · [ waiting · ] stray
]
0
[
1
]
2
[
3
Scan left to right and cancel every matched [ ] pair with a stack counter. Only the brackets that never find a partner need swaps.