Minimum Number of Swaps to Make the String Balanced - Problem

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.

Input & Output

Example 1 — Basic Unbalanced Case
$ Input: s = "]]][[["
Output: 2
💡 Note: We have 3 closing brackets followed by 3 opening brackets. Need 2 swaps: swap positions 0,3 and 1,4 to get "[[][]]" which is balanced.
Example 2 — Already Balanced
$ Input: s = "[]"
Output: 0
💡 Note: String is already balanced with proper opening and closing bracket pairs, so no swaps needed.
Example 3 — Mixed Pattern
$ Input: s = "]]][[["
Output: 2
💡 Note: We have 3 closing brackets followed by 3 opening brackets, same as Example 1. Need 2 swaps to balance the string.

Constraints

  • 2 ≤ s.length ≤ 106
  • s.length is even
  • s consists of exactly s.length/2 opening brackets '[' and s.length/2 closing brackets ']'

Visualization

Tap to expand
Minimum Swaps to Make String Balanced INPUT s = "]]][[[" ] ] ] [ [ [ 0 1 2 3 4 5 Unmatched ] Unmatched [ Length: n = 6 Opening '[': 3 Closing ']': 3 Currently Unbalanced! 3 closing brackets appear before any opening bracket ALGORITHM STEPS 1 Traverse String Count unmatched ] brackets 2 Track Balance balance-- for ], balance++ for [ 3 Find Max Imbalance Track minimum balance value 4 Calculate Swaps swaps = (unmatched + 1) / 2 Balance Tracking: idx: 0 1 2 3 4 5 chr: ] ] ] [ [ [ bal:-1 -2 -3 -2 -1 0 Min balance = -3 Unmatched ] = 3 FINAL RESULT Formula: swaps = (3 + 1) / 2 = 2 Swap Operations: Swap 1: ] at 0 --> [ at 5 Swap 2: ] at 1 --> [ at 4 Balanced Result: [[][]] Output: 2 Key Insight: Each swap can fix TWO unmatched brackets at once! When we swap a ']' from the left with a '[' from the right, both become correctly positioned. So minimum swaps = ceiling(unmatched / 2) = (unmatched + 1) / 2. Time: O(n) | Space: O(1) - Greedy approach counting unmatched closing brackets. TutorialsPoint - Minimum Number of Swaps to Make the String Balanced | Greedy Approach
Asked in
Facebook 15 Amazon 12 Microsoft 8
46.1K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen