Minimum Number of Swaps to Make the String Balanced

Medium

Topics
StringStackGreedyTwo Pointers

s has an even length and holds only the characters [ and ], with exactly as many of each.

A string is balanced when every bracket is matched and properly nested. In one move you may swap any two characters, which need not be adjacent. Return the fewest moves needed to make s balanced.

Example 1

s]0[1]2[3
open brackets waiting0101
a closing bracket with nothing to close
Balancing ][][ takes 1 swap. The lower row is how many opening brackets are still waiting to be closed at each position, and a ] that arrives when that figure is zero has nothing to pair with — those are shaded, and there are 1 here. One swap repairs two of them at once, by exchanging the leftmost stray ] with the rightmost stray [, which is why the answer is half that count rounded up rather than the count itself.
The two bracket counts are equal to begin with, so only the order is ever wrong.
Input:  s = "][]["
Output: 1
Explanation: Swapping the first and last characters gives "[[]]", which is balanced.

Example 2

s]0]1]2[3[4[5
open brackets waiting000123
a closing bracket with nothing to close
Input:  s = "]]][[["
Output: 2
Explanation: Three brackets are unmatched on the way through, and each swap fixes two of them.

Example 3

s[0]1
open brackets waiting10
Nothing is stray, so the string is already balanced and no swap is needed.
Input:  s = "[]"
Output: 0
Explanation: Already balanced, so nothing needs doing.

Constraints

  • 2 <= s.length <= 10^6
  • s.length is even
  • s consists only of the characters [ and ]
  • The counts of [ and ] are equal
Editorial — intuition, approach, complexity and pitfalls

Intuition

Because the counts of the two brackets are already equal, nothing is missing — the string is only in the wrong order. So the question is how much disorder there is, measured in swaps.

Scan left to right tracking how many opening brackets are currently unmatched. A [ raises it, a ] lowers it. The string is balanced exactly when that running figure never goes below zero.

When it does go below zero, you have met a ] with nothing to close. Those are the characters that have to move. Count how many there are at the worst point of the scan — or equivalently, cancel each ] against an available [ and see how many ] are left over.

The step that makes the answer small is noticing what a single swap buys. Swapping the leftmost unmatched ] with the rightmost unmatched [ repairs two problems at once, which is why the answer is (leftover + 1) / 2 rounded up rather than the leftover count itself. Three leftovers take two swaps, not three.

Approach

  1. Walk the string keeping a count of unmatched opening brackets.
  2. On [, increment it. On ], decrement it if it is positive, and otherwise record one unmatched closing bracket.
  3. After the scan, let leftover be the number of unmatched closing brackets.
  4. Each swap fixes two of them, so the answer is (leftover + 1) / 2 using integer division — which rounds up.
  5. Equivalently, track the most negative the running balance reaches; the answer is (|minimum| + 1) / 2.

Walkthrough

s = "]]][[["

running count of unmatched [
   ]   nothing open, so this ] is unmatched   leftover 1
   ]   unmatched                              leftover 2
   ]   unmatched                              leftover 3
   [   open 1
   [   open 2
   [   open 3

leftover = 3
answer (3 + 1) / 2 = 2

and two swaps really do suffice:
   ]]][[[
   swap position 0 with position 5  ->  []][[]
   swap position 1 with position 4  ->  [[]][]  balanced

why one swap fixes two
   taking the leftmost unmatched ] and the rightmost
   unmatched [ and exchanging them turns ...]...[...
   into ...[...]..., repairing the deficit at the left
   AND the surplus at the right in a single move.

s = "][]["
   ]   unmatched         leftover 1
   [   open 1
   ]   closes it         open 0
   [   open 1
   leftover = 1
   answer (1 + 1) / 2 = 1

Complexity

  • Time — O(n): one pass with two counters.
  • Space — O(1): two counters; no stack is needed since only the depth matters.

Common Pitfalls

  • Returning the leftover count rather than half of it rounded up. A swap fixes two problems, not one.
  • Rounding down. Three leftovers need two swaps, so the division has to round up.
  • Using an actual stack of brackets. Only the count of unmatched openers matters, and at a million characters the stack is pure overhead.
  • Assuming swaps must be adjacent. They need not be, which is exactly why one swap can fix two distant problems.
  • Checking that the counts of the two brackets are equal. The problem already guarantees it, so a balanced result is always reachable.

Full Solution — all languages

class Solution:
    def minSwaps(self, s):
        open_count = 0
        leftover = 0            # unmatched closing brackets

        for ch in s:
            if ch == "[":
                open_count += 1
            elif open_count > 0:
                open_count -= 1
            else:
                leftover += 1

        # One swap repairs two unmatched brackets -- the leftmost stray ]
        # and the rightmost stray [ -- so this rounds up.
        return (leftover + 1) // 2
SensAI
Beta
Tap the mic to stop voice mode