Minimum Number of Swaps to Make the String Balanced (LeetCode 1963): Solution and Explanation
The string has the same number of [ and ], and you may swap any two brackets. Return the fewest swaps that make it balanced. For ][][ one swap is enough, and ]]][[[ needs two.
Intuition
A bracket that already closes an earlier [ never needs to move, so cancel every matched pair first. A left-to-right scan with a counter of waiting [ does exactly that.
A ] that arrives while no [ is waiting can never be fixed from the left. These strays all appear before the [ that stay unmatched at the end, so the leftover always has the shape ]]...][[...[ with k of each.
Swapping the first stray ] with the second leftover [ turns ]][[ into [][]: one swap repairs two pairs. So the answer is ceil(k / 2).
Approach: Cancel matched pairs with a counter
- Set
open = 0, the number of[still waiting for a partner. - For each character: on
[incrementopen. - On
], ifopen > 0it closes a waiting[, so decrementopen. Otherwise it is a stray and is simply skipped. - At the end
openequalsk, the number of unmatched pairs. Return(open + 1) / 2.
Step-by-step example
s = "][]["
- Index 0 is
]and nothing is waiting, so it is a stray.open = 0. - Index 1 is
[: it waits.open = 1. - Index 2 is
]: it closes the[at index 1.open = 0. - Index 3 is
[: it waits.open = 1. - One stray
]and one waiting[remain, sok = 1and the answer isceil(1 / 2) = 1. Swapping index 0 with index 3 gives[[]].
Code: Python, Java, C++
1class Solution:
2 def minSwaps(self, s: str) -> int:
3 open_count = 0
4 for ch in s:
5 if ch == '[':
6 open_count += 1
7 elif open_count > 0:
8 open_count -= 1
9 return (open_count + 1) // 21class Solution {
2 public int minSwaps(String s) {
3 int open = 0;
4 for (char ch : s.toCharArray()) {
5 if (ch == '[') {
6 open++;
7 } else if (open > 0) {
8 open--;
9 }
10 }
11 return (open + 1) / 2;
12 }
13}1class Solution {
2public:
3 int minSwaps(string s) {
4 int open = 0;
5 for (char ch : s) {
6 if (ch == '[') {
7 open++;
8 } else if (open > 0) {
9 open--;
10 }
11 }
12 return (open + 1) / 2;
13 }
14};Time and space complexity
O(n)
One pass over the string with constant work per character.
O(1)
Only the counter is stored. The stack of waiting [ never needs to hold anything but its size.
Other approaches
Explicit stack (time O(n), space O(n))
Push every [ and pop on a matching ]. The stack size at the end is k. It is the same idea but uses O(n) memory for nothing.
Greedy two-pointer swaps (time O(n), space O(n) for a mutable copy)
Track the running balance; whenever it goes negative, swap the current ] with the rightmost [ found by a pointer moving in from the end, and count the swap. This produces an actual swap sequence and is also linear.
Common mistakes
- Returning
kinstead ofceil(k / 2). Each swap fixes two unmatched pairs, not one. - Using
k / 2with integer division. Fork = 3that gives 1, but two swaps are needed. - Letting the counter go negative on a stray
]. A stray must be ignored, otherwise it would cancel a later[that comes after it, which is not a valid match.
Frequently asked questions
Why does the leftover always look like ]]][[[?
A stray ] is only recorded when no [ is waiting. Any [ before it has already been matched, so every unmatched [ must come after every stray ].
Why does one swap fix two pairs?
In ]][[, swapping the first ] with the second [ gives [][], which is balanced. Applying this to each group of two unmatched pairs needs ceil(k / 2) swaps, and no swap can fix more than two.
How is this different from Minimum Add to Make Parentheses Valid?
Both cancel matched pairs with a counter. There you insert characters, so each unmatched bracket costs one. Here you swap, and a single swap repairs two pairs.