Minimum Number of Swaps to Make the String Balanced

Medium Stack Stack Basics

Minimum Number of Swaps to Make the String Balanced is a medium stack problem solved with the stack basics pattern. The best approach, optimal (count unmatched closers), runs in O(n) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from simulate the swaps (rescan from the right) up.

Problem

You are given a string s of even length n made only of square brackets. Exactly half of its characters are opening brackets '[' and the other half are closing brackets ']'.

A bracket string is balanced when every closing bracket can be paired with an earlier opening bracket, with pairs properly nested. Formally, the empty string is balanced; if A and B are balanced then so is AB; and if A is balanced then so is [A].

In one move you may pick any two positions of the string, not necessarily next to each other, and swap their characters. Return the minimum number of swaps needed to make s balanced.

Examples

Example 1

Input
s = "][]["
Output
1
Why
The first character is a closer with nothing open before it. Swapping it with the last character gives "[[]]", which is balanced, so one swap is enough.

Example 2

Input
s = "]]][[["
Output
2
Why
Three closers come before any opener. Swapping position 0 with position 5 gives "[]][[]", and then swapping position 2 with position 3 gives "[][][]". One swap can fix at most two of the three bad closers, so two swaps are needed.

Example 3

Input
s = "[]"
Output
0
Why
The string is already balanced, so no swap is needed.

Constraints

  • n == s.length
  • 2 <= n <= 10^6
  • n is even.
  • s[i] is either '[' or ']'.
  • s contains exactly n / 2 opening and n / 2 closing brackets.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Simulate the swaps (rescan from the right)O(n²)O(n)
Stack of unmatched bracketsO(n)O(n)
Optimal (count unmatched closers)O(n)O(1)

1Simulate the swaps (rescan from the right)

TimeO(n²)Up to n / 4 swaps can happen, and each one may rescan a long tail of closers from the right end.
SpaceO(n)The mutable copy of the string.

Walk from left to right and keep a balance: plus one for an opener, minus one for a closer. The first time the balance drops below zero, the current closer has nothing to match. Fix it right away by swapping it with the rightmost opener, found by scanning from the end. Count the swap and carry on with the balance set to one, since the swapped-in opener is now open.

  1. Copy s into a char array c and set swaps = 0, balance = 0.
  2. For each index i, add one to balance for '[' and subtract one for ']'.
  3. If balance < 0, scan j down from the end until c[j] == '['. Swap c[i] and c[j], add one to swaps, and set balance = 1.
  4. Return swaps.
class Solution {
    public int minSwaps(String s) {
        char[] c = s.toCharArray();
        int swaps = 0, balance = 0;
        for (int i = 0; i < c.length; i++) {
            balance += c[i] == '[' ? 1 : -1;
            if (balance < 0) {
                int j = c.length - 1;
                while (c[j] != '[') j--;
                c[i] = '[';
                c[j] = ']';
                swaps++;
                balance = 1;
            }
        }
        return swaps;
    }
}

2Stack of unmatched brackets

TimeO(n)Each character is pushed at most once and popped at most once.
SpaceO(n)In the worst case, such as all closers first, every character stays on the stack.

Use a stack to cancel every pair that already matches: push an opener, and when a closer arrives with an opener on top, pop that opener. Whatever stays on the stack can never match by itself, and it always reads as k closers followed by k openers. Swapping the first leftover closer with the last leftover opener fixes two of these pairs at once, so the answer is k divided by two, rounded up.

  1. Create an empty stack of characters.
  2. For each character ch of s: if ch is ']' and the top of the stack is '[', pop. Otherwise push ch.
  3. The stack now holds k closers and k openers, so k = stack size / 2.
  4. Return (k + 1) / 2.
class Solution {
    public int minSwaps(String s) {
        Deque<Character> stack = new ArrayDeque<>();
        for (char ch : s.toCharArray()) {
            if (ch == ']' && !stack.isEmpty() && stack.peek() == '[') stack.pop();
            else stack.push(ch);
        }
        int k = stack.size() / 2;
        return (k + 1) / 2;
    }
}

3Optimal (count unmatched closers)

TimeO(n)One pass over the string with constant work per character.
SpaceO(1)Only two integer counters.

The stack only ever holds openers that are still waiting, and closers that found nothing. So two counters do the same job: open counts the waiting openers, and unmatched counts the closers that arrived when open was zero. Each swap repairs two unmatched closers, and a lone last one still needs its own swap, so the answer is (unmatched + 1) / 2.

  1. Set open = 0 and unmatched = 0.
  2. For each character: on '[' add one to open. On ']' with open > 0, subtract one from open, since it matches. On ']' with open == 0, add one to unmatched.
  3. Return (unmatched + 1) / 2, which is unmatched divided by two, rounded up.
class Solution {
    public int minSwaps(String s) {
        int open = 0, unmatched = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '[') open++;
            else if (open > 0) open--;
            else unmatched++;
        }
        return (unmatched + 1) / 2;
    }
}

Edge cases to test

  • Already balanced string (answer 0)
  • Shortest input "][", which needs one swap
  • All closers first, then all openers, such as "]]]][[[[" (the most swaps for that length)
  • An odd number of unmatched closers: the last one still costs a whole swap, so round up
  • Unmatched closers spread out between balanced pieces, such as "[]][]["

Hints

Hint 1

Pairs that already match never need to move. Cancel them, the way a stack cancels matching brackets. What shape is left over?

Hint 2

After every match is cancelled, the leftover is always some closers followed by the same number of openers, like "]]][[[".

Hint 3

One swap of the first leftover closer with the last leftover opener fixes two unmatched pairs at once. So the answer is the number of unmatched closers, divided by two and rounded up.

FAQ

What is the best time complexity for Minimum Number of Swaps to Make the String Balanced?

Optimal (count unmatched closers) runs in O(n) time and O(1) extra space. One pass over the string with constant work per character.

Which pattern does Minimum Number of Swaps to Make the String Balanced use?

It is a stack problem that uses the stack basics pattern. Other problems with the same pattern: Valid Parentheses, Baseball Game, Asteroid Collision.

Is there a brute force solution for Minimum Number of Swaps to Make the String Balanced?

Yes. Simulate the swaps (rescan from the right) takes O(n²) time and O(n) space. Walk from left to right and keep a balance: plus one for an opener, minus one for a closer.

Which edge cases should I test for Minimum Number of Swaps to Make the String Balanced?

Already balanced string (answer 0); Shortest input "][", which needs one swap; All closers first, then all openers, such as "]]]][[[[" (the most swaps for that length); An odd number of unmatched closers: the last one still costs a whole swap, so round up; Unmatched closers spread out between balanced pieces, such as "[]][][".