Skip to content
LC-1963 Medium LeetCode

1963. Minimum Number of Swaps to Make the String Balanced

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 78% Topics: Two Pointers, String, Stack, Greedy
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(1)

class Solution(object):
    def minSwaps(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = curr = 0
        for c in s:
            if c == ']':
                curr += 1
                result = max(result, curr)
            else:
                curr -= 1
        return (result+1)//2

Solution from kamyu104/LeetCode-Solutions · MIT