The Indian Engineer

Problem 1963 Minimum Number of Swaps to Make the String Balanced

Posted on 7 mins

Two-Pointers String Stack Greedy

Problem Statement

Link - Problem 1963

Question

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.

Example 1:

Input: s = "][]["
Output: 1
Explanation: You can make the string balanced by swapping index 0 with index 3.
The resulting string is "[[]]".

Example 2:

Input: s = "]]][[["
Output: 2
Explanation: You can do the following to make the string balanced:
- Swap index 0 with index 4. s = "[]][][".
- Swap index 1 with index 5. s = "[[][]]".
The resulting string is "[[][]]".

Example 3:

Input: s = "[]"
Output: 0
Explanation: The string is already balanced.

Constraints:

Solution

class Solution {
public:
    int minSwaps(string s) {
        stack<char> st;
        int unbalanced = 0;
        for (int i = 0; i < s.size(); i++) {
            char ch = s[i];
            if (ch == '[')
                st.push(ch);
            else {
                if (!st.empty()) st.pop();
                else
                    unbalanced++;
            }
        }
        // we do (unbalanceed+1)/2 becauze we are removing all the balanced pairs using st and
        // whatever non-balanced count is remaining is to be paired , thats why /2 is done
        // 1 is added to do ceil(unbalanced/2) thats all
        return (unbalanced + 1) / 2;
    }
};

Complexity Analysis

| Algorithm             | Time Complexity | Space Complexity |
| --------------------- | --------------- | ---------------- |
| Stack-based iteration | O(n)            | O(n)             |

Explanation

Intial Thoughts

To solve this problem, consider a string as a series of opening and closing brackets. Think of balancing a string like building a tower with blocks, where each opening bracket is like adding a block and each closing bracket is like removing a block. The tower is balanced if at every step, the number of blocks added is greater than or equal to the number of blocks removed. Consider the process of examining the string from left to right, keeping track of the balance between opening and closing brackets encountered so far. Think of how a stack can be used to track this balance. Note that a swap can only happen between two different types of brackets, and consider how the process can be simplified by focusing on the minimum number of swaps needed. Consider how to handle cases where there are more closing brackets than opening brackets in the initial part of the string. Think about the strategy of always trying to balance the string as soon as possible, which may involve swapping a closing bracket with an opening bracket that appears later in the string.

Intuitive Analysis

Intuitively, the solution involves recognizing that to balance a string, each opening bracket must be paired with a closing bracket. Analyze how using a stack can help track the balance of opening and closing brackets. Consider how each time a closing bracket is encountered when the stack is empty, it means there is an unbalanced closing bracket that needs to be swapped with a later opening bracket. Think about how counting these unbalanced closing brackets and then dividing by 2 gives the minimum number of swaps needed, because each swap can balance two brackets. Realize that adding 1 before dividing by 2 is a way to perform a ceiling function, ensuring that if there is an odd number of unbalanced closing brackets, the result is still rounded up to the nearest whole number. Consider how this approach works because it effectively removes all the balanced pairs using the stack and whatever unbalanced count is remaining is to be paired, thus requiring the division by 2.

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity:


Footnote

This question is rated as Medium difficulty.

Hints

Iterate over the string and keep track of the number of opening and closing brackets on each step.

If the number of closing brackets is ever larger, you need to make a swap.

Swap it with the opening bracket closest to the end of s.


Similar Questions:

Title URL Difficulty
Remove Invalid Parentheses https://leetcode.com/problems/remove-invalid-parentheses Hard
Minimum Add to Make Parentheses Valid https://leetcode.com/problems/minimum-add-to-make-parentheses-valid Medium
Minimum Remove to Make Valid Parentheses https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses Medium
Minimum Insertions to Balance a Parentheses String https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string Medium