Leetcode Daily Question 08/10/2024 - 1963. Minimum Number of Swaps to Make the String Balanced

Problem Description:

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.

Solution:

class Solution:
  def minSwaps(self, s: str) -> int:
    unmatched_open = 0
    for char in s:
      if char == "[":
        unmatched_open += 1
      else:
        if unmatched_open > 0:
          unmatched_open -= 1
    return (unmatched_open + 1) // 2

Explanation:

The key to this question is to note that there exist one swap that pairs two unmatched open brackets with two unmatched closed brackets.

With this in mind, we traverse s to find the number of unmatched open brackets.

To calculate the number of swaps, we first calculate the number of unmatched pairs, then divide them by 2 to know how many swaps are required.

def minSwaps(s):
  unmatched_open = 0
  for char in s:
    if char == "[":
      unmatched_open += 1
    else:
      if unmatched_open > 0:
        unmatched_open -= 1
  return (unmatched_open + 1) // 2

The time complexity is O(n) as we traverse the string exactly once.

The space complexity is O(1) as we only store constant variables.

The full solution can be found near the top of the page.

Back