Magicsheet logo

Minimum Number of Swaps to Make the String Balanced

Medium
71.3%
Updated 6/1/2025

Minimum Number of Swaps to Make the String Balanced

1. What is this problem about?

Given a string of square brackets '[' and ']', you need to find the minimum number of swaps to make the string balanced. A balanced string is one where every opening bracket has a corresponding closing bracket in the correct order. Interestingly, you can swap any two characters, and you want to achieve balance in the fewest moves possible.

2. Why is this asked in interviews?

This is a popular question at companies like Microsoft, Google, and Adobe because it requires a clever observation that simplifies the problem. While it looks like a stack problem (which it is, initially), the "swap" aspect adds a greedy layer. It tests if a candidate can see through the complexity to find a simple mathematical relationship between "unbalanced" pairs and the number of swaps.

3. Algorithmic pattern used

The pattern is Greedy with a Stack-based logic (though you can simulate the stack with a simple counter). You traverse the string and remove all balanced pairs. You'll be left with a string of the form "]]][[[". The number of swaps needed to fix k unbalanced pairs is (k + 1) / 2.

4. Example explanation

String: "][]["

  • Encounter ']': Balance = -1 (unbalanced)
  • Encounter '[': Balance = 0 (this '[' doesn't fix the previous ']')
  • Encounter ']': Balance = -1
  • Encounter '[': Balance = 0 Wait, a better way to track: only track the "max depth" of unbalanced closing brackets. In "][][", we have 2 closing brackets that don't have a preceding opening bracket. Max unbalanced = 2. Swaps = (2 + 1) / 2 = 1. Swap the first ']' and last '[': "[][]" (Balanced!).

5. Common mistakes candidates make

Many try to use a standard stack and perform actual swaps in a simulation, which is difficult and prone to errors. Others struggle to derive the (k+1)/2 formula. A frequent mistake is thinking you need to swap every single unbalanced bracket, whereas a single swap can actually resolve two unbalanced pairs if done strategically.

6. Interview preparation tip

For bracket problems, always start by "canceling out" valid pairs. Whatever remains is the core of the problem. Often, the remaining string will have a very predictable structure (like all ']' followed by all '['), making it much easier to solve.

Similar Questions