Leetcode 1963: Minimum Number of Swaps to Make the String Balanced

grid47
grid47
Exploring patterns and algorithms
Apr 24, 2024 5 min read

You are given a string s of even length n. The string contains exactly n/2 opening brackets [ and n/2 closing brackets ]. A string is called balanced if for every opening bracket there exists a corresponding closing bracket, with each closing bracket having a matching opening bracket before it. Your task is to return the minimum number of swaps needed to make the string balanced.
Problem
Approach
Steps
Complexity
Input: The input consists of a string `s` of even length `n` consisting only of the characters `[` and `]`.
Example: s = "][]["
Constraints:
• 2 <= n <= 10^6
• s[i] is either '[' or ']'
• The number of opening brackets '[' equals n / 2, and the number of closing brackets ']' equals n / 2.
Output: Return the minimum number of swaps required to make the string balanced.
Example: Output: 1
Constraints:
• The output must be a single integer representing the minimum number of swaps.
Goal: The goal is to minimize the number of swaps by calculating how many unbalanced opening and closing brackets there are in the string.
Steps:
• Step 1: Iterate through the string and use a stack to track unmatched opening brackets.
• Step 2: Whenever a closing bracket is found, check if there is an unmatched opening bracket to pair it with.
• Step 3: Count the number of unmatched opening brackets and compute the necessary swaps.
Goal: The constraints ensure the problem is solvable within the input limits.
Steps:
• The input string contains only brackets and is of even length.
• The number of opening and closing brackets are equal.
Assumptions:
• The input string will always contain an equal number of opening and closing brackets.
Input: Input: s = '][][', Output: 1
Explanation: In this example, the first closing bracket `]` needs to be swapped with the last opening bracket `[`. After the swap, the string becomes balanced.

Input: Input: s = ']]][[[', Output: 2
Explanation: In this case, we need two swaps to balance the string. First, swap the 1st and 4th brackets, then swap the 2nd and 5th.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus