Skip to main content

Minimum Number of Swaps to Make the String Balanced - Solution & Explanation

MediumTwo PointersStringStackGreedy17 min readAsked at: Amazon, Microsoft, Meta +9
Practice this problem

Problem Statement

You are given a 0-indexed string s of even length n. The string consists of exactly n / 2 opening brackets '[' and n / 2 closing brackets ']'.

A string is called balanced if and only if:

  • It is the empty string, or
  • It can be written as AB, where both A and B are balanced strings, or
  • It can be written as [C], where C is a balanced string.

You may swap the brackets at any two indices any number of times.

Return the minimum number of swaps to make s balanced.

 

Example 1:

Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".

Example 2:

Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".

Example 3:

Input: s = "[]"
Output: 0
Explanation: The string is already balanced.

 

Constraints:

  • n == s.length
  • 2 <= n <= 106
  • n is even.
  • s[i] is either '[' or ']'.
  • The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.

Approach Overview

Problem Overview: You are given a string consisting only of '[' and ']'. The string contains equal numbers of both brackets but may be unbalanced. The goal is to compute the minimum number of swaps needed to transform it into a valid balanced bracket sequence.

Approach 1: Greedy Using Balance Count (O(n) time, O(1) space)

This approach scans the string once while tracking the current bracket balance. Increment the balance for '[' and decrement for ']'. When the balance becomes negative, it means a closing bracket appears before a matching opening bracket. At that point you conceptually perform a swap with a future '['. Each time this happens, increase the swap counter and reset the balance to 1 because the swap effectively inserts a valid opening bracket before the closing one.

The key insight is that you never need to physically perform swaps. Counting imbalance is enough because every time the prefix becomes invalid, one swap will fix it. This greedy logic works since each correction locally restores validity and guarantees the minimal number of swaps. The method runs in linear time and constant space and is the cleanest solution for this problem. This pattern commonly appears in greedy and string balancing problems.

Approach 2: Two-Pointer Swap Simulation (O(n) time, O(1) space)

The two-pointer strategy simulates the swaps explicitly. Maintain a left pointer scanning for imbalance and a right pointer searching for the next available '[' that can fix it. When the prefix becomes invalid (more ']' than '['), move the right pointer backward until a '[' is found and swap it with the problematic closing bracket.

This technique directly demonstrates why each imbalance requires a swap. After the swap, continue scanning from the left while maintaining the balance count. The algorithm still runs in O(n) time because each pointer moves at most once across the string. This approach is useful for understanding the mechanics of fixing invalid bracket sequences and often appears in problems using two pointers or stack-like validation logic.

Recommended for interviews: The greedy balance-count approach is what interviewers usually expect. It shows you recognize the imbalance pattern and can solve it with a single pass and constant memory. Demonstrating the two-pointer simulation first can help explain the intuition, but the greedy counting method highlights stronger algorithmic insight.

Approach 1: Greedy Approach Using Balance Count

This approach involves traversing the string and counting the balance between opening and closing brackets. You increase a count when you find an opening bracket and decrease the count when you find a closing bracket. If at any point the count goes negative, a swap is needed to balance out the string, and the swap count is incremented. The final swap count will be the required number of swaps to make the string balanced.

This solution maintains a balance count by iterating over the characters of the string. It increases the balance for each opening bracket '[' encountered and decreases it for each closing bracket ']'. Whenever the balance goes negative, a swap is needed to make balance non-negative, hence the count of swaps is incremented along with a correction of balance at that point. This provides the minimum number of swaps needed.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of string s.
Space Complexity: O(1), as no extra space is used aside from a few variables.

Try this approach in the editor →

Approach 2: Two-Pointer Approach

This approach uses two pointers to traverse the string efficiently. One pointer starts from the beginning of the string, and the other starts at the end. Using these pointers, swaps are performed when an excessive number of closing brackets on one side can be paired with an opening bracket on the other side.

Two pointers are initialized at the start and end of the string. The inner mismatched brackets are swapped until the string becomes balanced. The solution ensures that excessive closing brackets found earlier are balanced by swapping them with opening brackets found later in the string.

Code

C

C++

Java

Python

C#

JavaScript

Complexity

Time Complexity: O(n), where n is the length of string s, due to traversing the string once.
Space Complexity: O(1), as we're only using constants amount of space for pointers and variables.

Try this approach in the editor →

Approach 3: Greedy

We use a variable x to record the current number of unmatched left brackets. We traverse the string s, for each character c:

  • If c is a left bracket, then we increment x by one;
  • If c is a right bracket, then we need to check whether x is greater than zero. If it is, we match the current right bracket with the nearest unmatched left bracket on the left, i.e., decrement x by one.

After the traversal, we will definitely get a string of the form "]]]...[[[...". We then greedily swap the brackets at both ends each time, which can eliminate 2 unmatched left brackets at a time. Therefore, the total number of swaps needed is \left\lfloor \frac{x + 1}{2} \right\rfloor.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Complexity Comparison

ApproachComplexity
Greedy Approach Using Balance Count

Time Complexity: O(n), where n is the length of string s.
Space Complexity: O(1), as no extra space is used aside from a few variables.

Two-Pointer Approach

Time Complexity: O(n), where n is the length of string s, due to traversing the string once.
Space Complexity: O(1), as we're only using constants amount of space for pointers and variables.

Greedy—

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Greedy Using Balance CountO(n)O(1)Best general solution; minimal logic and optimal complexity
Two-Pointer Swap SimulationO(n)O(1)Useful for understanding how swaps fix imbalance step by step

Video Solution

Minimum Number of Swaps to Make String Balanced - Leetcode 1963 Weekly Contest - Python • NeetCode • 51,974 views views

Watch 9 more video solutions →

Frequently Asked Questions

Is Minimum Number of Swaps to Make the String Balanced easy or hard?
The problem is rated Medium because the logic requires recognizing the imbalance pattern rather than performing literal swaps. Once the greedy observation is clear, the implementation becomes straightforward with a single pass and constant memory.
Minimum Number of Swaps to Make the String Balanced Python/Java solution
Most implementations follow the same logic: iterate through the string, update the balance counter, and count swaps when the balance becomes negative. The algorithm is short and works identically in Python, Java, C++, C#, and JavaScript because it relies only on simple counters.
How to solve Minimum Number of Swaps to Make the String Balanced in O(n)?
Iterate through the string and maintain a balance counter. Increase it for '[' and decrease it for ']'. If the balance becomes negative, it means a closing bracket appears too early, so increment the swap count and reset the balance to 1 to simulate swapping with a future '['. Continue until the end of the string.
What is the best approach for Minimum Number of Swaps to Make the String Balanced?
The greedy balance counting approach is the most efficient solution. Scan the string once while tracking the difference between opening and closing brackets. Whenever the balance becomes negative, increment the swap counter and reset the balance to reflect the conceptual swap. This runs in O(n) time with O(1) space.
Is Minimum Number of Swaps to Make the String Balanced asked at Google/Amazon/Meta?
Bracket balancing and swap minimization problems frequently appear in interviews at companies like Amazon, Google, and Meta. Variants of this question test understanding of greedy logic, stack behavior, and string processing in linear time.
What data structure is used in Minimum Number of Swaps to Make the String Balanced?
The optimal approach does not require complex data structures. A simple integer balance counter is enough to track unmatched brackets. Conceptually the problem relates to stack-based bracket validation, but the greedy method eliminates the need for an actual stack.
What is the time complexity of Minimum Number of Swaps to Make the String Balanced?
The optimal solution runs in O(n) time because the string is scanned once. Only a few integer counters are maintained, so the space complexity is O(1). Even the two-pointer simulation version remains linear because each pointer moves across the string at most once.

Ready to solve this problem?

Practice Minimum Number of Swaps to Make the String Balanced with our built-in code editor and test cases.

Practice on FleetCode