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:
AB, where both A and B are balanced strings, or[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.
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.
Constraints:
n == s.length2 <= n <= 106n is even.s[i] is either '[' or ']'.'[' equals n / 2, and the number of closing brackets ']' equals n / 2.Problem Overview: You are given a string consisting only of '[' and ']'. The string contains equal numbers of both brackets but may be unbalanced. The goal is to compute the minimum number of swaps needed to transform it into a valid balanced bracket sequence.
Approach 1: Greedy Using Balance Count (O(n) time, O(1) space)
This approach scans the string once while tracking the current bracket balance. Increment the balance for '[' and decrement for ']'. When the balance becomes negative, it means a closing bracket appears before a matching opening bracket. At that point you conceptually perform a swap with a future '['. Each time this happens, increase the swap counter and reset the balance to 1 because the swap effectively inserts a valid opening bracket before the closing one.
The key insight is that you never need to physically perform swaps. Counting imbalance is enough because every time the prefix becomes invalid, one swap will fix it. This greedy logic works since each correction locally restores validity and guarantees the minimal number of swaps. The method runs in linear time and constant space and is the cleanest solution for this problem. This pattern commonly appears in greedy and string balancing problems.
Approach 2: Two-Pointer Swap Simulation (O(n) time, O(1) space)
The two-pointer strategy simulates the swaps explicitly. Maintain a left pointer scanning for imbalance and a right pointer searching for the next available '[' that can fix it. When the prefix becomes invalid (more ']' than '['), move the right pointer backward until a '[' is found and swap it with the problematic closing bracket.
This technique directly demonstrates why each imbalance requires a swap. After the swap, continue scanning from the left while maintaining the balance count. The algorithm still runs in O(n) time because each pointer moves at most once across the string. This approach is useful for understanding the mechanics of fixing invalid bracket sequences and often appears in problems using two pointers or stack-like validation logic.
Recommended for interviews: The greedy balance-count approach is what interviewers usually expect. It shows you recognize the imbalance pattern and can solve it with a single pass and constant memory. Demonstrating the two-pointer simulation first can help explain the intuition, but the greedy counting method highlights stronger algorithmic insight.
This approach involves traversing the string and counting the balance between opening and closing brackets. You increase a count when you find an opening bracket and decrease the count when you find a closing bracket. If at any point the count goes negative, a swap is needed to balance out the string, and the swap count is incremented. The final swap count will be the required number of swaps to make the string balanced.
This solution maintains a balance count by iterating over the characters of the string. It increases the balance for each opening bracket '[' encountered and decreases it for each closing bracket ']'. Whenever the balance goes negative, a swap is needed to make balance non-negative, hence the count of swaps is incremented along with a correction of balance at that point. This provides the minimum number of swaps needed.
Time Complexity: O(n), where n is the length of string s.
Space Complexity: O(1), as no extra space is used aside from a few variables.
This approach uses two pointers to traverse the string efficiently. One pointer starts from the beginning of the string, and the other starts at the end. Using these pointers, swaps are performed when an excessive number of closing brackets on one side can be paired with an opening bracket on the other side.
Two pointers are initialized at the start and end of the string. The inner mismatched brackets are swapped until the string becomes balanced. The solution ensures that excessive closing brackets found earlier are balanced by swapping them with opening brackets found later in the string.
Time Complexity: O(n), where n is the length of string s, due to traversing the string once.
Space Complexity: O(1), as we're only using constants amount of space for pointers and variables.
We use a variable x to record the current number of unmatched left brackets. We traverse the string s, for each character c:
c is a left bracket, then we increment x by one;c is a right bracket, then we need to check whether x is greater than zero. If it is, we match the current right bracket with the nearest unmatched left bracket on the left, i.e., decrement x by one.After the traversal, we will definitely get a string of the form "]]]...[[[...". We then greedily swap the brackets at both ends each time, which can eliminate 2 unmatched left brackets at a time. Therefore, the total number of swaps needed is \left\lfloor \frac{x + 1}{2} \right\rfloor.
The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).
Python
Java
C++
Go
TypeScript
| Approach | Complexity |
|---|---|
| Greedy Approach Using Balance Count | Time Complexity: O(n), where n is the length of string s. |
| Two-Pointer Approach | Time Complexity: O(n), where n is the length of string s, due to traversing the string once. |
| Greedy | — |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Greedy Using Balance Count | O(n) | O(1) | Best general solution; minimal logic and optimal complexity |
| Two-Pointer Swap Simulation | O(n) | O(1) | Useful for understanding how swaps fix imbalance step by step |
Minimum Number of Swaps to Make String Balanced - Leetcode 1963 Weekly Contest - Python • NeetCode • 51,204 views views
Watch 9 more video solutions →Practice Minimum Number of Swaps to Make the String Balanced with our built-in code editor and test cases.
Practice on FleetCode