LeetCode 1963: Minimum Number of Swaps to Make the String Balanced Solution

Master LeetCode problem 1963 (Minimum Number of Swaps to Make the String Balanced), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1963. Minimum Number of Swaps to Make the String Balanced

Problem Explanation

Explanation

To solve this problem, we can use a greedy approach. We iterate through the string and maintain the balance of opening and closing brackets. We keep track of the number of extra closing brackets encountered so far. If we encounter an opening bracket, we increment our balance. If we encounter a closing bracket and our balance is already positive (meaning we have extra closing brackets), we increment our swap count and decrement the balance.

The intuition behind this approach is that for a string to be balanced, each closing bracket should match with an opening bracket. By swapping, we can bring unmatched closing brackets closer to the opening brackets.

After iterating through the string, the number of swaps we made is the minimum number of swaps required to balance the string.

  • Time complexity: O(n) where n is the length of the input string.
  • Space complexity: O(1) as we are using constant extra space.

Solution Code

class Solution {
    public int minSwaps(String s) {
        int swaps = 0;
        int balance = 0;
        
        for (char c : s.toCharArray()) {
            if (c == '[') {
                balance++;
            } else {
                if (balance > 0) {
                    balance--;
                } else {
                    swaps++;
                }
            }
        }
        
        return swaps;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1963 (Minimum Number of Swaps to Make the String Balanced)?

This page provides optimized solutions for LeetCode problem 1963 (Minimum Number of Swaps to Make the String Balanced) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1963 (Minimum Number of Swaps to Make the String Balanced)?

The time complexity for LeetCode 1963 (Minimum Number of Swaps to Make the String Balanced) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1963 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1963 in Java, C++, or Python.

Back to LeetCode Solutions