Minimum number of swaps for bracket balancing

Pattern: Balanced brackets

medium

Scan left to right. When a ] arrives while there are more ] than [ so far, it waits. When the next [ arrives, it must move left past every waiting ], costing that many adjacent swaps, and the imbalance drops by one.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a string of n [ and n ], return the fewest swaps of neighbouring characters that make it balanced. "[]][][" gives 2; "[[][]]" gives 0.

The catalogue has no practice link for this one.

Think first

  • When is a ] a problem?
  • Where must the fix come from?
  • How many swaps does one [ need to move past k waiting ]?

Hints

    Brute force, and why it fails

    Simulate: whenever the balance goes negative, find the next [ and bubble it left one swap at a time: O(n²).

    The key insight

    You never need to move the brackets: each [ that arrives while ] are waiting pays the number waiting, and fixes one of them.

    Dry run

    imbalance0
    swaps0

    s = "[]][][". [ then ] are fine: imbalance 0.

    Step 1 of 4

    The plan

    open = close = imbalance = swaps = 0
    for c in s:
        if c == '[':
            open += 1
            if imbalance > 0: swaps += imbalance; imbalance -= 1
        else:
            close += 1; imbalance = close - open
    return swaps
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with counters.

    Edge cases

    • Already balanced: 0.
    • ]]][[[: 6.
    • ][: 1.
    I've built my logic, show the code

    Java

    class Solution {
        public int swapCount(String s) {
            int open = 0, close = 0;                // '[' and ']' seen so far
            int imbalance = 0;                      // how many ']' are waiting for a '['
            int swaps = 0;
            for (char c : s.toCharArray()) {
                if (c == '[') {
                    open++;
                    if (imbalance > 0) {
                        swaps += imbalance;         // this '[' must move left past every waiting ']'
                        imbalance--;
                    }
                } else {
                    close++;
                    imbalance = close - open;       // more ']' than '[' so far
                }
            }
            return swaps;
        }
    }

    C++

    class Solution {
    public:
        int swapCount(string s) {
            int open = 0, close = 0;                // '[' and ']' seen so far
            int imbalance = 0;                      // how many ']' are waiting for a '['
            int swaps = 0;
            for (char c : s) {
                if (c == '[') {
                    open++;
                    if (imbalance > 0) {
                        swaps += imbalance;         // this '[' must move left past every waiting ']'
                        imbalance--;
                    }
                } else {
                    close++;
                    imbalance = close - open;       // more ']' than '[' so far
                }
            }
            return swaps;
        }
    };

    Python

    class Solution:
        def swapCount(self, s: str) -> int:
            opened = closed = imbalance = swaps = 0  # imbalance: how many ']' are waiting for a '['
            for c in s:
                if c == "[":
                    opened += 1
                    if imbalance > 0:
                        swaps += imbalance          # this '[' must move left past every waiting ']'
                        imbalance -= 1
                else:
                    closed += 1
                    imbalance = closed - opened     # more ']' than '[' so far
            return swaps

    Common mistakes

    • Counting the imbalance after the swap instead of before.
    • Treating this as the reversal problem: swaps and reversals have different answers.

    Similar problems