Minimum Number of Swaps to Make the String Balanced (LeetCode 1963): Solution and Explanation

Medium
Two Pointers
String
Stack
Greedy

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

  1. Set open = 0, the number of [ still waiting for a partner.
  2. For each character: on [ increment open.
  3. On ], if open > 0 it closes a waiting [, so decrement open. Otherwise it is a stray and is simply skipped.
  4. At the end open equals k, the number of unmatched pairs. Return (open + 1) / 2.

Step-by-step example

s = "][]["
  1. Index 0 is ] and nothing is waiting, so it is a stray. open = 0.
  2. Index 1 is [: it waits. open = 1.
  3. Index 2 is ]: it closes the [ at index 1. open = 0.
  4. Index 3 is [: it waits. open = 1.
  5. One stray ] and one waiting [ remain, so k = 1 and the answer is ceil(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) // 2
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the string with constant work per character.

Space

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 k instead of ceil(k / 2). Each swap fixes two unmatched pairs, not one.
  • Using k / 2 with integer division. For k = 3 that 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.