#1963

Minimum Number of Swaps to Make the String Balanced

pupil · 460 · lc medium +26 · premium · verified · 78.2% accepted · 2,562 likes · top 89%

Description

A 0-indexed string s of even length n contains exactly n / 2 copies of '[' and n / 2 copies of ']'. A bracket string is balanced when it is empty, expressible as two back-to-back balanced strings, or a balanced string wrapped in [C].

You may swap characters at any two positions any number of times. Return the minimum number of swaps needed to make s balanced.

Example 1:

Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".

Example 2:

Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".

Example 3:

Input: s = "[]"
Output: 0
Explanation: The string is already balanced.

Code

1
2
3