Minimum Number of Swaps to Make the String Balanced

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.
I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.
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 bothAandBare balanced strings, orIt can be written as
[C], whereCis 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.
LeetCode Problem - 1963
class Solution {
public int minSwaps(String s) {
int openBracketCounter = 0; // Counter to track unmatched open brackets
// Iterate through each character of the string
for(char ch : s.toCharArray()){
if(ch == '['){ // If the character is an open bracket
openBracketCounter++; // Increment the open bracket counter
} else if (openBracketCounter > 0){ // If we find a closing bracket and there are unmatched open brackets
openBracketCounter--; // Match the closing bracket by decrementing the open bracket counter
}
}
// Since each swap can fix two unmatched brackets, we divide by 2 (and add 1 to ensure rounding)
return (openBracketCounter + 1) / 2;
}
}




