You are given a string s of even length n. It contains exactly n / 2 opening brackets [ and exactly n / 2 closing brackets ].
A string is balanced if it is empty, or it can be written as AB where A and B are both balanced, or it can be written as [C] where C is balanced.
In one swap you exchange the brackets at any two indices, and you may swap as many times as you like. Return the minimum number of swaps needed to make s balanced.
Function Signature
def min_swaps(s: str) -> int:
Rules
-
The two indices in a swap do not need to be adjacent.
-
The counts of
[
and
]
are equal, so some sequence of swaps always balances the string and an answer always exists.
-
Return
0
when
s
is already balanced.
Constraints
-
n == len(s)
-
2 <= n <= 10^6
-
n
is even.
-
Each
s[i]
is
[
or
]
.
-
s
contains exactly
n / 2
characters
[
and
n / 2
characters
]
.
Examples
Input: s = "][]["
Output: 1
Swapping index 0 with index 3 gives "[[]]", which is balanced. The input is not balanced, so at least one swap is needed.
Input: s = "]]][[["
Output: 2
Swapping index 0 with index 4 gives "[]][][", and then swapping index 1 with index 5 gives "[[][]]". One swap cannot be enough: it changes at most one of the first three characters, so the first three characters would still hold more ] than [.
Input: s = "[]][]["
Output: 1
Swapping index 2 with index 5 gives "[][[]]", which is balanced. The leading "[]" is already matched and needs no work.