> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Minimum Number of Swaps to Make the String

> Tested Python solution for LeetCode 1963 with 28 pytest cases. Generate a practice environment with lcpy.

LeetCode 1963, [Medium](/catalog/medium). Topics: [Two Pointers](/catalog/topics/two-pointers), [String](/catalog/topics/string), [Stack](/catalog/topics/stack), [Greedy](/catalog/topics/greedy), Bracket Sequences. [View on LeetCode](https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced/description/).

Generate this problem as a practice environment: tested reference solution, 28 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1963   # by problem number
lcpy gen -s minimum_number_of_swaps_to_make_the_string_balanced   # by problem name
```

## 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 both `A` and `B` are **balanced** strings, or
* It can be written as `[C]`, where `C` is 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*.

### Examples

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

```
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 "[[][]]".
```

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

### Constraints

* n == s.length
* 2 \<= n \<= 10^6
* n is even.
* s\[i] is either '\[' or ']'.
* The number of opening brackets '\[' equals n / 2, and the number of closing brackets ']' equals n / 2.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_number_of_swaps_to_make_the_string_balanced/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/minimum_number_of_swaps_to_make_the_string_balanced/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(1)
    def min_swaps(self, s: str) -> int:
        unmatched_close = 0
        max_unmatched_close = 0
        for ch in s:
            if ch == "]":
                unmatched_close += 1
                max_unmatched_close = max(max_unmatched_close, unmatched_close)
            else:
                unmatched_close -= 1
        return (max_unmatched_close + 1) // 2
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(1) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.