Skip to content
LC-1541 Medium LeetCode

1541. Minimum Insertions to Balance a Parentheses String

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

class Solution(object):
    def minInsertions(self, s):
        """
        :type s: str
        :rtype: int
        """
        add, bal = 0, 0
        for c in s:
            if c == '(':
                if bal > 0 and bal%2:
                    add += 1
                    bal -= 1
                bal += 2
            else:
                bal -= 1
                if bal < 0:
                    add += 1
                    bal += 2
        return add + bal

Solution from kamyu104/LeetCode-Solutions · MIT