Skip to content

1963. Minimum Number of Swaps to Make the String Balanced 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int minSwaps(string s) {
    // Cancel out all the matched pairs, then we'll be left with "]]]..[[[".
    // The answer is ceil(the number of unmatched pairs / 2).
    int unmatched = 0;

    for (const char c : s)
      if (c == '[')
        ++unmatched;
      else if (unmatched > 0)  // c == ']' and there's a match.
        --unmatched;

    return (unmatched + 1) / 2;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int minSwaps(String s) {
    // Cancel out all the matched pairs, then we'll be left with "]]]..[[[".
    // The answer is ceil(the number of unmatched pairs / 2).
    int unmatched = 0;

    for (final char c : s.toCharArray())
      if (c == '[')
        ++unmatched;
      else if (unmatched > 0) // c == ']' and there's a match.
        --unmatched;

    return (unmatched + 1) / 2;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def minSwaps(self, s: str) -> int:
    # Cancel out all the matched pairs, then we'll be left with ']]]..[[['.
    # The answer is ceil(# of unmatched pairs // 2).
    unmatched = 0

    for c in s:
      if c == '[':
        unmatched += 1
      elif unmatched > 0:  # c == ']' and there's a match.
        unmatched -= 1

    return (unmatched + 1) // 2