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:

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

Return the minimum number of swaps to make s balanced.

Input: s = "][]["
Output: 1
Explanation: You can string balanced by swapping index 0 with index 3 and the resulting string will be [[]]
Input: s = "]]][[["
Output: 2
Explanation: You can do the following swaps to make the string balanced:
- Swap index 0 with 4, and the resulting string will be "[]][][".
- Swap index 1 with index 5, and the resulting string will be "[[][]]".
Input: s = "[]"
Output: 0
Explanation: Input string is already balanced.
Constraints:

Contents

In this approach, we are going to use a Stack to store opening bracket '[' from input string s, and then when we find a closing bracket ']' we will balance them and no swapping is required, if the stack is empty, that means we will need a swap to make it balanced.

Let's look at an example, say if the input string is "]]][[["

import java.util.Stack; public class MinSwapsToMakeStringBalanced { static int usingStack(String s) { Stack<Character> stack = new Stack<>(); int swaps = 0; for(char c : s.toCharArray()) { if(c == '[') { stack.push(c); } else { if(stack.isEmpty()) { // If the stack is empty, then a swap is needed swaps++; } else { stack.pop(); // Balance closing brackets with previous open bracket } } } return (swaps + 1)/2; // +1 to cover edge cases, where number of pairs to correct could be odd // divide by 2 is because each swap operation will correct two unbalanced brackets } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input string s
Space complexity: O(n) since we are storing opening brackets '[' in a stack.

This is similar to above solution, instead of storing the opening brackets in a stack, we will maintain them in a variable imbalanceCount.

public class MinSwapsToMakeStringBalanced { static int usingKeepingTrackOfClosingBrackets(String s) { int imbalanceCount = 0; int swaps = 0; for(char c: s.toCharArray()) { if(c == '[') { imbalanceCount++; } else { imbalanceCount--; } //If imbalanceCount is negative, make a swap to make it balance if(imbalanceCount <0){ swaps++; // Now, reset the count to 0, to continue imbalanceCount =0; } } return (swaps +1) /2; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of input string s
Space complexity: O(1) since we are only two variables imbalanceCount to keep track of brackets and swaps variable to keep the count of swaps needed.

Above implementations source code can be found at GitHub link for Java code