Minimum Insertions to Balance a Parentheses String — LeetCode 1541 Python Solution

MediumStackGreedyString
Problem
#1541
Pattern
Stack
Reading time
4 min

The problem

Given a parentheses string s containing only the characters '(' and ')'. A parentheses string is balanced if: Any left parenthesis '(' must have a corresponding two consecutive right parenthesis '))'.

Example

Input
s = "(()))"
Output
1
Explanation
The second '(' has two matching '))', but the first '(' has only ')' matching. We need to add one more ')' at the end of the string to be "(())))" which is balanced.

Python solution

Python
class Solution:
    def minInsertions(self, s: str) -> int:
        ans = x = 0
        i, n = 0, len(s)
        while i < n:
            if s[i] == '(':
                # 待匹配的左括号加 1
                x += 1
            else:
                if i < n - 1 and s[i + 1] == ')':
                    # 有连续两个右括号,i 往后移动
                    i += 1
                else:
                    # 只有一个右括号,插入一个
                    ans += 1
                if x == 0:
                    # 无待匹配的左括号,插入一个
                    ans += 1
                else:
                    # 待匹配的左括号减 1
                    x -= 1
            i += 1
        # 遍历结束,仍有待匹配的左括号,说明右括号不足,插入 x << 1 个
        ans += x << 1
        return ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1541. Minimum Insertions to Balance a Parentheses String is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1541. Minimum Insertions to Balance a Parentheses String?
LeetCode 1541. Minimum Insertions to Balance a Parentheses String is rated Medium on LeetCode.
What topics does LeetCode 1541. Minimum Insertions to Balance a Parentheses String cover?
LeetCode 1541. Minimum Insertions to Balance a Parentheses String is tagged Stack, Greedy and String on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview