Problem Statement

Minimum Number of Swaps to Make the String Balanced - LeetCode

Pattern:


Solution

public int minSwaps(String s) {
	int stackSize = 0, rev = 0;        // reversal count
 
	for (char ch : s.toCharArray())
		if(ch == '[') stackSize++;
		else {
			if(stackSize == 0) {
				stackSize++;
				rev++;
			}
			else stackSize--;
		}
 
	// if unbalanced brackets left
	if(stackSize != 0) 
		if(stackSize % 2 == 0) rev = rev + stackSize / 2;
		else return -1;
 
	return (rev+2-1)/2;
}

TC : SC :

Notes