MediumTwo PointersStringStackGreedyUpdated Sep 2026

1963. Minimum Number of Swaps to Make the String Balanced

Asked at Visa

Difficulty

Medium

Time

O(n)

Space

O(1)

Pattern

Two Pointers

Companies

1

Problem

You get a string s made only of [ and ]. The length is even, and there are exactly as many [ as ]. A string is balanced when every [ has a matching ] to its right, like [[]] or [][].

You may swap the characters at any two positions, as many times as you like. Return the minimum number of swaps needed to turn s into a balanced string.

Key idea: a swap can move a ] from the front to the back and a [ from the back to the front at the same time. So one swap can fix more than one problem spot.

What we are asked to do

s][][0123Index 0 holds ']' and index 3 holds '[' — swappingthem gives "[[]]"
The string "][][" is not balanced, and one swap of the first and last characters fixes it.

Constraints

  • ●2 <= n <= 10^6
  • ●n == s.length
  • ●n is even
  • ●s[i] is either '[' or ']'
  • ●The number of '[' equals n / 2, and the number of ']' equals n / 2

Examples

Example 1
Inputs = "][]["
Output1
WhySwap index 0 with index 3. The string becomes "[[]]", which is balanced. One swap is enough, and zero swaps cannot work because the string starts with ']'.
Example 2
Inputs = "]]][[["
Output2
WhySwap index 0 with index 4 to get "[]][][", then swap index 1 with index 5 to get "[[][]]". Two swaps are needed because three ']' characters sit before any matching '['.
Example 3
Inputs = "[]"
Output0
WhyThe string is already balanced, so no swap is needed.

Asked At

1 companies
CompanyDifficulty
VisaMediumView all Visa questions →

How to Think About It

1

Matched pairs never need to move. Cancel them with a stack (or just a counter of open brackets).

2

What is left after cancelling is some number m of ] followed by m of [, like ]]][[[.

3

Key insight: one swap of the first unmatched ] with the last unmatched [ turns ]...[ into [...] and fixes two pairs at once (the swapped pair and the one next to it). So the answer is ceil(m / 2).

4

Count m with one variable: open tracks unmatched [. On ], if open > 0 it matches (open -= 1), otherwise it is an unmatched ] (m += 1).

5

Walkthrough: "]]][[[": m = 3 -> (3 + 1) // 2 = 2 swaps.

Optimal Approach

Step 1: open = 0, unmatched = 0.
Step 2: For each char: [ -> open += 1; ] -> if open > 0, open -= 1, else unmatched += 1.
Step 3: Return (unmatched + 1) // 2.

Time: O(n). Space: O(1).

Cancel pairs, then count leftovers

stack]]]frontbackStep 1 — for "]]][[[", the first three ']' have no '['before them, so they stay unmatchedleftover]]][[[012345Step 2 — the leftovers look like ]]] [[[ ; swappingthe first ']' with the last '[' fixes two pairsunmatched m = 3answer = (m + 1) // 2 = 2
Matched pairs are removed. What remains is always some ']' followed by some '[', and one swap fixes two of them.
ComplexityTime O(n)Space O(1)We scan the string once and keep only two counters, so time grows linearly with the string length and memory stays constant.

What Trips People Up in Real Interviews

1

Answering m swaps instead of ceil(m / 2). Each well-chosen swap fixes two pairs.

2

Simulating swaps on the string. Only the count matters.

3

Confusing swaps with insertions or deletions (as in Minimum Add to Make Parentheses Valid).

4

Not justifying why the leftover pattern is always ]...][...[.

Solution Code

O(n) time
def minSwaps(s):
    open_count = unmatched = 0
    for ch in s:
        if ch == '[':
            open_count += 1
        elif open_count > 0:
            open_count -= 1
        else:
            unmatched += 1
    return (unmatched + 1) // 2

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Minimum Number of Swaps to Make the String Balanced problem?

Minimum Number of Swaps to Make the String Balanced gives you a string of equally many `[` and `]` characters and asks for the fewest swaps (of any two positions) to make the brackets balanced. After cancelling every matched pair, what remains is always `]]]...[[[`, and one swap fixes two of the leftover pairs.

How do you solve Minimum Number of Swaps to Make the String Balanced?

The optimal approach runs in O(n) time and O(1) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Minimum Number of Swaps to Make the String Balanced?

Minimum Number of Swaps to Make the String Balanced is asked at Visa. It is a medium difficulty problem.

What are common mistakes on Minimum Number of Swaps to Make the String Balanced?
  • Answering `m` swaps instead of `ceil(m / 2)`. Each well-chosen swap fixes two pairs.
  • Simulating swaps on the string. Only the count matters.
  • Confusing swaps with insertions or deletions (as in Minimum Add to Make Parentheses Valid).
  • Not justifying why the leftover pattern is always `]...][...[`.