LeetCode solutions

2095. Minimum Number of Swaps to Make the String Balanced

My accepted Python solution to LeetCode problem 2095, Minimum Number of Swaps to Make the String Balanced, running in 447ms.

  • Difficulty: Medium
  • Python
  • Runtime 447ms
  • Memory 24.8MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 447ms, memory 24.8MB, accepted 2026-01-01.

python
class Solution:
    def minSwaps(self, s: str) -> int:
        # Count unmatched closing brackets
        # Every swap can fix 2 unmatched brackets
        unmatched = 0
        max_unmatched = 0
        for c in s:
            if c == '[':
                unmatched -= 1
            else:  # c == ']'
                unmatched += 1
            max_unmatched = max(max_unmatched, unmatched)
        # Each swap fixes 2 unmatched brackets
        return (max_unmatched + 1) // 2

Source