Problem Description
Given an even-length string s containing exactly n/2 opening brackets '[' and n/2 closing brackets ']', determine the minimum number of swaps required to make s balanced. A string is balanced if it is empty, or it can be decomposed into two balanced strings, or it can be written as "[C]" where C is balanced.
Key Insights
- The challenge revolves around identifying imbalance during a single pass through the string.
- Using a counter (balance) helps track the difference between opening and closing brackets.
- When the counter goes negative, it indicates an excess of closing brackets, meaning a swap is needed.
- Performing a swap effectively converts a problematic closing bracket into an opening bracket, hence resetting the local imbalance.
- This greedy approach, processing the string from left to right, guarantees a minimal number of swaps.
Space and Time Complexity
Time Complexity: O(n) where n is the length of the string s.
Space Complexity: O(1) as only constant extra space is used.
Solution
The solution uses a greedy algorithm with a single pass through the string. A variable "balance" counts the net number of opening brackets. For each character:
- If the character is '[', increment balance.
- If the character is ']', decrement balance.
- When balance becomes negative, it means that at that point there are more closing brackets than opening ones; hence, a swap is needed. Increase the swap counter and reset balance to 1 (simulating the swap where the closing bracket is effectively turned into an opening one). This approach efficiently computes the minimum swaps required.