Skip to main content

Command Palette

Search for a command to run...

Minimum Number of Swaps to Make the String Balanced

Published
1 min read
Minimum Number of Swaps to Make the String Balanced
G

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 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.

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; 
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.